Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
341 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...