aJax请求,等待它完成

时间:2016-07-05 15:27:26

标签: javascript ajax google-maps

即时通讯使用Google API,我想让地图上标有多个地址,以便我使用Geocoder。然而,我的其余代码在此Geocoder返回结果之前运行!

// Handle addresses
var addressesHandled = [];
function handleAddresses(addressObj) {
    for (i = 0; i < addressObj.length; i++) {
        addressesHandled[i] = new Address(addressObj[i]['title'], addressObj[i]['address'], addressObj[i]['latlng'], addressObj[i]['defaultOpen']);
    }
}
// Address object
function Address(title, address, latlng, defaultOpen) {
    this.title = title;
    this.address = address;

    this.latlng = latlng;
    if (latlng == undefined) {
        this.latlng = codeAddress(address);
    }

    this.defaultOpen = defaultOpen;
}

正如您所看到的,如果未定义lat和lng值,我会浏览每个对象并获取地址。如果这些是未定义的,那么我执行codeAddress函数,它将从当前地址获取lat和lng值,但是我认为在发生这种情况时脚本的其余部分仍在运行!

下面是codeAddress函数,我以为我无法返回结果但是现在我认为它根本就不是返回得足够快。

如何修复此问题,以便我的其余脚本等待,直到每个地址都有lat和lng计算!?

function codeAddress(address, callback) {
    var geocoder;
    geocoder = new google.maps.Geocoder();

    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var loc = [];
            // loc = { lat: results[0].geometry.location.lat(), lng: results[0].geometry.location.lng() };
            loc[0] = results[0].geometry.location.lat(); loc[1] = results[0].geometry.location.lng();
            console.log(loc);

            callback(loc);
        } else {
            console.log("Geocode was not successful for the following reason: " + status);
        }
    });
}

修改 嗯,我只是觉得处理标记并将其添加到地图会更容易,因为每个地理编码功能都会返回结果吗?

0 个答案:

没有答案