反向地理编码器返回未定义

时间:2013-02-05 01:09:18

标签: javascript html google-maps-api-3 google-geocoder

所以,我正在使用google的反向地理编码器,所以我最初做的是输入一个地址,比如tokyo,然后我让latlng拿到latlng并将其放回地理编码器以获得该位置的正确名称但是相反,它只返回undefined。我的代码是:

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;
  }
});

名称每次最终都是未定义的,有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:2)

Geocoder是异步的,你需要在其回调函数中使用Geocoder返回的数据(未经测试):

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

相关问题