Search code examples
javascriptgoogle-mapsundefinedgoogle-geocoder

Google map Geocoder


I Using the google geocoder to get the lat and lng, when initMap had been called, I got two alert, first value is undefined ,and second get the lat value, what is the problem to get the undefined value, and how to resolve this? I need to get the value immediately.

function initMap(){
      var addr = '1600 Amphitheatre Parkway, Mountain View, CA';
      var code = getLatLng(addr);
      alert(code.lat); // --> alert_1
}

function getLatLng(addr) {
    var geocoder = new google.maps.Geocoder();
     geocoder.geocode({'address': addr }, function (results, status) {
       var lat,lng = 0;
         if (status == google.maps.GeocoderStatus.OK) {
              lat = results[0].geometry.location.lat();
              lng = results[0].geometry.location.lng();
         }
         alert(lat); // --> alert_2
         return {lat : lat,lng : lng};
     });
 }

Solution

  • The function geocode is an asynchronous function. Therefore, you get undefined for code.lat in the alert of the initMap function and the geocoded value in the getLatLng function. You can add a callback function to the parameters of the getLatLng function to solve your problem like this:

    function initMap() {
      var addr = '1600 Amphitheatre Parkway, Mountain View, CA';
      getLatLng(addr, function(code) {
        alert(code.lat);
      });
    }
    
    function getLatLng(addr, cb) {
      var geocoder = new google.maps.Geocoder();
      geocoder.geocode({'address': addr }, function (results, status) {
        var lat,lng = 0;
          if (status == google.maps.GeocoderStatus.OK) {
            lat = results[0].geometry.location.lat();
            lng = results[0].geometry.location.lng();
          }
          cb({lat: lat, lng: lng});
      });
    }