Reverse Geocoder Returning undefined

[亡魂溺海] 提交于 2019-12-02 14:30:47

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/14698570/reverse-geocoder-returning-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!