Search code examples
javascripthtmlgoogle-maps-api-3google-geocoder

Reverse Geocoder Returning undefined


So, I am using google's reverse geocoder, so what I originally do is enter an address such as, tokyo, then I get that latlng take the latlng and place it back into the geocoder to receive the proper name of the location but instead it just returns undefined. My code is:

var geocoder = new google.maps.Geocoder();
var place = document.getElementById("location").value;
var name;
var place_latlng;
geocoder.geocode({'address' : place}, function(results, status){
  if (status == google.maps.GeocoderStatus.OK){
    place_latlng = results[0].geometry.location;
    addMarker(place_latlng);
  }
});
geocoder.geocode({'latLng' : place_latlng},function(results, status){
  if (status == google.maps.GeocoderStatus.OK){
    name = results[0].formatted_address;
  }
});

name ends up being undefined every time, is there a way I can fix this?


Solution

  • The Geocoder is asynchronous, you need to use the data returned by the Geocoder inside its callback function (not tested):

    geocoder.geocode({'address' : place}, function(results, status){
      if (status == google.maps.GeocoderStatus.OK){
        place_latlng = results[0].geometry.location;
        addMarker(place_latlng);
        geocoder.geocode({'latLng' : place_latlng},function(results, status){
          if (status == google.maps.GeocoderStatus.OK){
            name = results[0].formatted_address;
            alert("name = "+name);
          } else { alert("reverse geocode of "+place_latlng+ " failed ("+status+")"); }
        });
      } else { alert("geocode of "+place+" failed ("+status+")"); }
    });
    

    Example