Google Geocode API的回调函数不会立即执行

时间:2014-10-28 09:43:58

标签: javascript google-maps google-geocoder

当我单步执行此代码时,这就是我观察到的行为:响应处理程序代码被跳过,直到函数的其余部分结束,然后处理程序代码执行。这当然不是我想要的,因为响应之后的代码取决于响应处理程序中的代码。

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
}

导致此行为的原因是什么,如何更改代码以确保回调在其下方的代码之前运行?

1 个答案:

答案 0 :(得分:1)

Geocode以异步方式运行,因此您必须将该代码放入回调中,或者创建另一个回调函数:

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
});

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();
});
相关问题