just wondering if someone can help me with a Javascript principle. I’m guessing this is pretty core if I want to pass a function as a parameter. I know a little about Javascript but I admit possibly not enough about its subtleties.
So, codeAddress is invoked, then my first alert (HERE2) is reached, code passes back to my showOnMap function, then my second alert (HERE3) is reached. Why does my HERE3 alert show before my HERE2 alert? Is there anything I can do to tell Javascript to wait?
Thanks in advance
function showOnMap() {
var inputStart = document.getElementById('CurrentHitch_StartDescription').value;
var inputEnd = document.getElementById('CurrentHitch_EndDescription').value;
codeAddress(inputStart, true); //HERE1*************
codeAddress(inputEnd, false);
var bounds2 = new google.maps.LatLngBounds(this.markerStart.getPosition());
bounds2.extend(this.markerEnd.getPosition());
map.fitBounds(bounds2);
alert('showOnMap'); //HERE3*************
}
function codeAddress(address, isStart) {
geocoder.geocode({ 'address': address }, function (results, status) {
alert('codeAddress'); //HERE2*************
if (status == google.maps.GeocoderStatus.OK) {
if (isStart) {
markerStart.setPosition(results[0].geometry.location);
}
else {
markerEnd.setPosition(results[0].geometry.location);
}
} else {
alert("Sorry, couldn't find your destination: " + status);
}
});
return;
}
It’s because
geocodeis happening asynchronously (non-blocking code, meaning sometime in the future, and I’ll let you know when I’m done). It might be possible to tell Google’s api to work synchronously (as blocking code), but you’d probably be better off putting code that depends on the results in the callback ofgeocode.