0

使用 google 地理位置 api 时,我被一个问题困扰了好几天。这是我一直在尝试的-

function codeAddress(address) {
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({"address": address}, function(results, status) {
        if (status == "OK") {
            return results[0].geometry.location;
        } else {
            return null;
        }
    });
}

function generateJSON(origin, destination) {
    var origin_loc = codeAddress(origin);
    var dest_loc = codeAddress(destination);
    ....
}

“origin_loc”变量返回未分配,我无法通过调试器找出原因。当我将结果 [0] 记录到控制台时,它会很好地返回对象。

有谁知道为什么会这样?

谢谢

4

1 回答 1

0

这最终对我有用 -

function codeAddresses(addresses, callback) {
    var coords = [];
    for(var i = 0; i < addresses.length; i++) {
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({'address':addresses[i]}, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                coords.push(results[0].geometry.location);
                if(coords.length == addresses.length) {
                    callback(coords);
                }
            }
            else {
                throw('No results found: ' + status);
            }
        });
    }
}

function generateJSON(origin, destination) {
    var addresses = [origin, destination];
    codeAddresses(addresses, function(coords) {
         var json = { ..... }
         ....
    });
}

感谢您的帮助@yuriy636!

于 2016-08-15T17:56:29.443 回答