2

我在 javascript 上使用地理编码器。我有一个名为 codeAddress 的函数,它接受地址并正确给出坐标。但是,当我在另一个函数中调用此函数时,我无法获得正确的结果,因为调用者函数在 codeAddress 函数之前结束。这是我的代码:

    var geocoder = new google.maps.Geocoder();
    var lokasyon ={ id:0,lat:0,lng:0 };
    var lokasyonlar=[];
    function codeAddress(adres, id) {
        geocoder.geocode({ 'address': adres }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                lokasyon.id = id;
                lokasyon.lat = results[0].geometry.location.lat();
                lokasyon.lng = results[0].geometry.location.lng();
                lokasyonlar.push(lokasyon);
                alert("codeAddress");
            } else {
                alert("Geocode was not successful for the following reason: " + status);
            }
        });
    }
    function trial2() {
        codeAddress("1.ADA SOKAK, ADALET, OSMANGAZİ, Bursa", 12);
        alert("trial2");
    }
    window.onload = trial2;

当我运行此代码时,首先显示“trial2”,然后显示“codeAddress”。这是什么原因?

4

1 回答 1

1

因为 geocoder.geocode() 方法要求谷歌服务器,它需要几秒钟。这意味着 geocode() 方法是异步的,并且 alert("trial2") 比回调更快。

如果你想在回调后执行代码'alert("trial2")',你需要改成这样:

function codeAddress(adres, id, callback) {
    geocoder.geocode({ 'address': adres }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            lokasyon.id = id;
            lokasyon.lat = results[0].geometry.location.lat();
            lokasyon.lng = results[0].geometry.location.lng();
            lokasyonlar.push(lokasyon);
            alert("codeAddress");
        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
        callback();
    });
}
function trial2() {
    codeAddress("1.ADA SOKAK, ADALET, OSMANGAZİ, Bursa", 12, function(){
      alert("trial2");
    });
}
于 2012-11-20T08:05:46.153 回答