我希望获得Google Maps API geocode()函数的结果,以便将其用于其他函数。我已经把下面的代码放在一个OnClick事件上,用来对地图上点击的点的地址进行反向地理编码。
它总是让点的上一个值被点击。例如:我第一次点击它时,它有‘未定义’,第二次它有我之前点击的点的地址,以此类推。
var address ;
my_listener = google.maps.event.addListener(map, 'click', function(event) {
   codeLatLng(event.latLng);
});
function codeLatLng(mylatLng) {
    geocoder = new google.maps.Geocoder();
    var latlng = mylatLng;
    geocoder.geocode({'latLng': latlng}, function(results, status) 
    {
        if (status == google.maps.GeocoderStatus.OK) 
        {
            if (results[1]) 
            {
                address = results[1].formatted_address;
            }
        }
    });
    alert(address);
}发布于 2012-07-04 19:55:06
如果您将alert移动到回调中,您将看到新地址:
geocoder.geocode({'latLng': latlng}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) 
    {
        if (results[1]) 
        {
            address = results[1].formatted_address;
            alert(address);   //moved here
        }//   ^
    }//       |
});//         |  
//-------------地理编码过程是异步的,因此在本例中:
geocoder.geocode({'latLng': latlng}, function(results, status) {
    //We be called after `alert(address);`
});
alert(address);在从服务器接收地理编码数据并调用回调function(results, status){}之前,将执行alert。
https://stackoverflow.com/questions/11328407
复制相似问题