问题
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