JamesGold
JamesGold

Reputation: 815

callback function for Google Geocode API not executing immediately

When I step through this code this is the behavior I observe: the response handler code is skipped over until the rest of the function finishes, and then the handler code executes. This is of course not what I want, because the code that comes after the response depends on the code in the response handler.

var geocoder = new google.maps.Geocoder();
function initializePlaces() {
    var destination_LatLng;
    var destination = document.getElementById("destination_address").value;
    geocoder.geocode( {'address': destination}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK)
        {
            destination_LatLng = results[0].geometry.location;
        } else if (status == google.maps.GeocoderStatus.ZERO_RESULTS) {
            alert("Bad destination address.");
        } else {
            alert("Error calling Google Geocode API.");
        }
    });
    // more stuff down here
}

What is causing this behavior, and how can I change my code to ensure the callback runs before the code below it?

Upvotes: 0

Views: 1185

Answers (1)

Johan Karlsson
Johan Karlsson

Reputation: 6476

Geocode runs asynchronously, so you have to either put that code inside the callback, or make another callback function:

geocoder.geocode( {'address': destination}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK)
    {
        destination_LatLng = results[0].geometry.location;
    } else if (status == google.maps.GeocoderStatus.ZERO_RESULTS) {
        alert("Bad destination address.");
    } else {
        alert("Error calling Google Geocode API.");
    }

    //put more stuff here instead
});

or

function moreStuff(){
    //more stuff here
}


geocoder.geocode( {'address': destination}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK)
    {
        destination_LatLng = results[0].geometry.location;
    } else if (status == google.maps.GeocoderStatus.ZERO_RESULTS) {
        alert("Bad destination address.");
    } else {
        alert("Error calling Google Geocode API.");
    }

    moreStuff();
});

Upvotes: 1

Related Questions