1

对于用户输入他的地址的网站,我试图找到离他最近的用户可以收集订购商品的位置。

根据用户的地址,我可以将可能的取货地点缩小到 2 到 5 个之间。所以我想计算用户地址(A 点)和可能的取货地点之间的距离。

此处的演示仅使用两个地址即可正常工作。我已经尽可能多地调整代码以使用两个以上的地址。我在这里发布了我的 JS 代码,因为我似乎无法在 SO 中正确格式化它。

代码中有两个警报。第一个警报正确显示了不同的取货地点。但第二个警报始终显示最后取货地点。

谁能解释为什么?


HTML:

<p id="hello">Hello World</p>

JavaScript:

var geocoder, location1, location2, gDir;

function initialize(counter) {    
    if( counter == 0 ){
        geocoder = new GClientGeocoder();
        gDir = new GDirections();
    }
    GEvent.addListener(gDir, "load", function() {
        var drivingDistanceMiles = gDir.getDistance().meters / 1609.344;
        var drivingDistanceKilometers = gDir.getDistance().meters / 1000;
        $("#results").append('<strong>Driving Distance: </strong>' + drivingDistanceKilometers + ' kilometers<br /><br />');        
    });
}

function getDistance(agency_add, counter) {
    initialize(counter);
    geocoder.getLocations(agency_add, function (response) {    
        if (!response || response.Status.code != 200) {
            alert("Sorry, we were unable to geocode the address" + agency_add);
        }
        else {
            location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
            //alert("ONE: "+location1.address);
            geocoder.getLocations(document.forms[0].address1.value, function (response) {
                //alert("TWO: "+location1.address);
                if (!response || response.Status.code != 200) {alert("Sorry, we were unable to geocode the second address");}
                else {                        
                    location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};                    
                    gDir.load('from: ' + location1.address + ' to: ' + location2.address);
                }
            });
        }
    });
}


$(document).ready(function(){
    //put each agency address in an array
    var agencies = [];    
    $(".agency_field").each(function(index) {
        agencies.push($(this).val());
    });

    for (var i = 0; i < agencies.length; i++){
        var res = getDistance(agencies[i], i);
    }    
});
4

1 回答 1

2

您在循环中调用 geocoder.getLocations 。geocoder.getLocations 异步运行。当它在处理第一个请求的同时接收到第二个请求时,它会取消第一个请求。

如果你想多线程 geocoder.getLocations 你需要创建它的多个实例。

于 2011-04-12T15:23:08.697 回答