Google Geocode API的回调函数没有立即执行

callback function for Google Geocode API not executing immediately

本文关键字:执行 函数 Geocode API 回调 Google      更新时间:2023-09-26

当我遍历这段代码时,我观察到的行为是:跳过响应处理程序代码,直到函数的其余部分完成,然后执行处理程序代码。这当然不是我想要的,因为响应之后的代码取决于响应处理程序中的代码。

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
}

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

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