1

情况如下:

  • 我们有 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]);

    }
}
});

谢谢你的帮助 !

4

0 回答 0