从Google Maps Geocoder获取返回值

时间:2014-05-28 21:28:13

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

我正在尝试根据Google地图地理编码器的lat-long坐标获取位置名称。我似乎无法从地理编码器回调中提取值。这是我的代码:

geocoder = new google.maps.Geocoder();
var address = "";
var lat = 54.1234;
var lng = -114.1234;
var latlng = new google.maps.LatLng(lat, lng);

geocoder.geocode({'latLng': latlng } , function(results,status) {

    if (status == google.maps.GeocoderStatus.OK) {
        address = results[1].formatted_address; //want to get this address
    } else {
        address = 'error';
    }
});

window.alert(address) 
//address is an empty string here, but I want the value from inside the geocoder
//want access to address here to do other operations with it

Google Developers网站上的地理编码器文档几乎不存在, 我试图找到一个类似的例子时遇到问题。我在这里不舒服,所以任何帮助 会很好!

1 个答案:

答案 0 :(得分:1)

调用是异步的,因此值存在于回调函数中:

geocoder.geocode({'latLng': latlng } , function(results,status) {
  if (status == google.maps.GeocoderStatus.OK) {
    address = results[1].formatted_address; //want to get this address
  } else {
    address = 'error';
  }
  window.alert(address);
});

// The code here runs before the callback function