DistanceMatrixService和多个回调同时进行

时间:2012-06-07 10:44:35

标签: javascript google-maps asynchronous callback

情况如下:

  • 我们有1个原始地址
  • 我们有x(admit 3)品牌,这些品牌本身就有x(admit 3)商店

我必须为每个品牌确定距离原始地址最近的商店。

问题是getDistanceMatrix回调函数是异步的,它们在同一时间同时执行。我不知道如何找到这样的回调对应这些品牌。

实际上,我得到了所有最近的商店,但我不知道如何将它们连接到各自的品牌。

这是我的代码:

//Origin address
var origin = "origin address";

//For each brands, list store's address
var brand1 = new Array("address1", "address2", "address3");
var brand5 = new Array("address1", "address2", "address3");
var brand29 = new Array("address1", "address2", "address3");

calculateDistance(1, brand1);
calculateDistance(5, brand5);
calculateDistance(29, brand29);

//Classic google code
function calculateDistance(id_brand, adresses){ 
    var service = new google.maps.DistanceMatrixService();
    service.getDistanceMatrix({
        origins: [origin],
        destinations: adresses,
        travelMode: google.maps.TravelMode.DRIVING,
        avoidHighways: false,
        avoidTolls: false,
    }, callback);
}

function callback(response, status) {
    var tabDistance = new Array();

    if (status == google.maps.DistanceMatrixStatus.OK) {  
        var origins = response.originAddresses;
        var destinations = response.destinationAddresses;

        for (var i = 0; i < origins.length; i++) {
            var results = response.rows[i].elements;
            for (var j = 0; j < results.length; j++) {
                var element = results[j];
                var distance = element.distance.value;
                var from = origins[i];
                var to = destinations[j];
                tabDistance[j] = new Array(distance,to);
            }
        }

        //Find the nearest store
        var indice = minDistance(tabDistance);

        alert('Nearest store ' + tabDistance[indice][0]);

    }
}
});

感谢您的帮助!

0 个答案:

没有答案