0

我有一个在 jQuery 数据表中显示城市列表的网页。我需要计算每个城市与单个给定位置的距离,并将结果放入表中。我能够遍历表的行并调用 Google 的 DistanceMatrix,然后在回调函数中正确读取结果。但是,在回调中,我需要用计算出的距离更新 jQuery 数据表中的一列。由于结果是异步到达的(只有结果和状态作为参数),我如何确定返回数组中的哪个结果适用于我的数据表行?

我想我可以在我的数据表中搜索每个结果元素中返回的城市,但是 DistanceMatrix 调用经常在返回之前将我的原始搜索参数转换(“地理编码”?)为更具体的位置字符串。

示例代码:

    var origins = ["Portland, OR"];
    for (var i = 0; i < oTable.fnGetNodes().length; i++) {
        //build a destinations array resembling the one spoofed in the next row
        //assume < 25 entries or else batch processing
    }
    var destinations = ["Seattle, WA", "San Francisco, CA"];

    var service = new google.maps.DistanceMatrixService();
    service.getDistanceMatrix({
        origins: origins,
        destinations: destinations,
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.DirectionsUnitSystem.IMPERIAL,
        avoidHighways: false,
        avoidTolls: false
    }, (function (response, status) {
        if (status == google.maps.DistanceMatrixStatus.OK) {
            for (var i = 0; i < response.originAddresses.length; i++) {
                var results = response.rows[i].elements;
                for (var j = 0; j < results.length; j++) {
                    var distance = response.rows[0].elements[j].distance.text;

                    //how do I know which row number to update?  Using j here doesn't match
                    //correctly on the order of rows.  I could search my data table on city but
                    //result (coded) values frequently differ from my table data

                    //var rowNumberToUpdate = ??;

                    oTable.fnUpdate(distance, *rowNumberToUpdate*, column6);
                }
            }
        }
    })
);
4

1 回答 1

0

The response reflects the order of origins and destinations used inside the request.

So you may use the index inside of rows to get the related address inside origins, and the index inside of rows.elements to get the related address inside destinations.

Inside the loop used inside the callback destinations[j] will return the used destination from destinations.

于 2012-03-24T00:32:36.730 回答