Can someone please explain to me the following behaviour:
function getLatLong()
{
var geocoder = new google.maps.Geocoder();
var result = "";
geocoder.geocode ( { 'address': "London", 'region': 'uk' }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
result = results[0].geometry.location;
alert('Im called second');
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
alert('Im called first');
return result;
}
How is the second alert message being called before the first alert? I have an issue whereby I’m trying to return to value of the assigned variable ‘result’ but it keeps returned as an empty string even though it does get assigned a value from results[0].geometry.location. I have a horrible feeling I’m missing something very obvious here :/
geocoder.geocode()is an asynchronous method, meaning that it returns immediately without blocking, but runs the specified function only once the geocoding call (presumably to Google’s geocoding service) has completed.What is happening is that the
alert('Im called first')call is called before the other call has completed, most likely because the geocoding call has to go over the internet. The order of these two calls can vary, purely based on how long the geocoding takes to complete.To solve this, you cannot return the result from this function. Instead, you need to supply a function to be called when the geocoding is complete to act as a callback so that you can then use the now filled-in result.
e.g.