Let’s say I have these geocoding calls:
function myFunction(marker1,marker2) {
var firstAddress = null;
var secondAddress = null;
geocoder.geocode({'latLng': marker1.getPosition()}, function(results, status) {
# if geocoding successful, set firstAddress
})
geocoder.geocode({'latLng': marker2.getPosition()}, function(results, status) {
# if geocoding successful, set secondAddress
})
return [firstAddress,secondAddress];
}
Let’s say I call myFunction. The geocode call is asynchronous, right? So it will execute and return quickly, calling the callback on results. Will the geocoding have finished when I return the addresses? How could I ensure that both functions finished before returning?
Short answer: no. You will almost immediately get to the return line of
myFunction, most likely well before the AJAX has completed.Your best bet is to force geoCoder’s requests to be synchronous. If you can’t, then what you will need to do is set a global flag indicating when both requests have completed and wait for that flag to be set. If it is, then you can gather your data, construct your array, and return it.
Be sure to add a
document.geoCodeRequestCompleteFlag++inside yourmarker1.getPosition()andmarker2.getPosition()callbacks.The downside to this, is that if your requests take a long time, the browser may kill your script.