Pass city name from Javascript to PHP in google maps

Asked

Viewed 43 times

0

I need to pass to PHP the name of the city coming from Javascript

I use this code to get the name of the city

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false&key="></script> 
<script type="text/javascript"> 
  var geocoder;

  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
} 
//Get the latitude and the longitude;
function successFunction(position) {
    var lat = position.coords.latitude;
    var lng = position.coords.longitude;
    codeLatLng(lat, lng)
}

function errorFunction(){
    alert("Geocoder failed");
}

  function initialize() {
    geocoder = new google.maps.Geocoder();



  }

  function codeLatLng(lat, lng) {

    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({'latLng': latlng}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
      console.log(results)
        if (results[1]) {
        alert (results[0].address_components[1].short_name);



         //formatted address
     //    alert(results[0].formatted_address)
        //find country name
             for (var i=0; i<results[0].address_components.length; i++) {
            for (var b=0;b<results[0].address_components[i].types.length;b++) {


            //there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
                if (results[0].address_components[i].types[b] == "locality") {
                    //this is the object you are looking for
                    city= results[0].address_components[i];
                    break;
                }
            }
        }
        //city data 
        //alert(city.long_name)


        } else {
          alert("No results found");
        }
      } else {
        alert("Geocoder failed due to: " + status);
      }
    });
  }
</script> 

It would be possible to pass the value of alert (results[0].address_components[1].short_name); for PHP?

  • When you say: upload to php, you’re actually saying you’re making an http request using php, so you’ve tried using Ajax? For example, you probably have some php file waiting for the request, right?

  • How could I put an Ajax inside Javascript? This would be just to show the site user the city he is in at the time he enters the site.

  • I get it, I’ll edit the answer.

1 answer

1


Basic example using Ajax:

Note that seu-arquivo-php.php is where you’ll be requesting.

var geocoder;
//Variável Criada
var nomeCidade;
if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
  var lat = position.coords.latitude;
  var lng = position.coords.longitude;
  codeLatLng(lat, lng)
}

function errorFunction() {
  alert("Geocoder failed");
}

function initialize() {
  geocoder = new google.maps.Geocoder();

}

function codeLatLng(lat, lng) {

  var latlng = new google.maps.LatLng(lat, lng);
  geocoder.geocode({
    'latLng': latlng
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      console.log(results)
      if (results[1]) {
        //alert ();

        nomeCidade = results[0].address_components[1].short_name;
        //Mostra o nome da cidade
        document.getElementById("cidade").innerText = nomeCidade;
        enviarDadoParaPHP(`cidade_nome=${results[0].address_components[1].short_name}`);


        //formatted address
        //    alert(results[0].formatted_address)
        //find country name
        for (var i = 0; i < results[0].address_components.length; i++) {
          for (var b = 0; b < results[0].address_components[i].types.length; b++) {


            //there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
            if (results[0].address_components[i].types[b] == "locality") {
              //this is the object you are looking for
              city = results[0].address_components[i];
              break;
            }
          }
        }
        //city data 
        //alert(city.long_name)


      } else {
        alert("No results found");
      }
    } else {
      alert("Geocoder failed due to: " + status);
    }
  });
}
//Usando Ajax no Javascript
function enviarDadoParaPHP(data) {
  //Isso é AJaxa ()
  //AJAX = Assíncrono Javascript XML.
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      //document.getElementById("result").innerHTML = this.responseText;
    }
  };
  xhttp.open("POST", "seu-arquivo-php.php", true);
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send(data);
}
<!DOCTYPE html>
<html lang="pt-br">

<head>
  <meta charset="utf-8">
  <title>Demo</title>
</head>

<body>
  <h1>Demo</h1>
  <p id="cidade">Nome da Cidade Aqui</p>
  <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false&key="></script>
</body>

</html>

  • how does the php file get city?

  • There are several things we need to take into consideration. For example: if you want to simply show the city name on a php page, you can do as in editing.

  • in your-file-php.php I put session_start(); echo $_SESSION['city']=$_POST['sendDadoParaPHP']; but it didn’t work

  • Try the following in your php file: $_SESSION['city']=$_POST['city_name'];

  • it worked ;) thank you

  • There is one problem: When I open the site it calls the php file and writes in the session the name of the city correctly, but I need to update the page again to see the name of the city. You could already show the name of the city without having to refresh the page?

  • Yes, there’s a way. If no one answers. Tomorrow, I’ll help you.

  • ok thanks for your attention

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.