Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...