Reputation: 1695
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 :/
Upvotes: 0
Views: 193
Reputation: 733
oThe reason is that the call the geocoder.geocode uses a callback to deliver the results. The call to geocoder.geocode only lasts long enough to send out a request to the geocoder service, and then execution continues to the next (non-callback) line, which is the "Im called first" alert. All of the code in the callback is "saved for later" and invoked when the geocoder response is received.
You will have to write your code accordingly. Instead of returning the result from your original function call, you will have to take the result inside the callback and continue processing from there. It can make javascript control flow a little hard to follow.
Upvotes: 1
Reputation: 83004
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.
function getLatLong(completeCallback)
{
var geocoder = new google.maps.Geocoder();
geocoder.geocode ( { 'address': "London", 'region': 'uk' }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var result = results[0].geometry.location;
completeCallback(result);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
Upvotes: 1