简体   繁体   English

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

[英]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? 是什么导致此行为,以及如何更改代码以确保回调在其下面的代码之前运行?

Geocode runs asynchronously, so you have to either put that code inside the callback, or make another callback function: 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
});

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM