Store result of Google Maps geocode function

[亡魂溺海] 提交于 2019-12-14 02:31:24

问题


I want to get the result of Google Maps API geocode() function in order to use it to other functions. I have put the code below on an OnClick event to reverse geocode the address of the point clicked on map.

It is always having the previous value of point clicked. Example: the first time i click it has 'undefined', 2nd time it has the address of the point i clicked before and so on.

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

回答1:


If you will move alert, inside of callback, you will see the new address:

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

Geocoding process is asyncronous, so in this case:

geocoder.geocode({'latLng': latlng}, function(results, status) {
    //We be called after `alert(address);`
});
alert(address);

alert will be executed before the geocoding data will be recieved from server and callback function(results, status){} will be called.



来源:https://stackoverflow.com/questions/11328407/store-result-of-google-maps-geocode-function

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