Google Distance Matrix API返回的结果不正确

时间:2018-05-28 20:51:28

标签: javascript api google-distancematrix-api

我正在使用Google Distance Matrix API来返回不同传输模式的旅行时间。虽然它有时有效,但似乎结果并不总是一致的,并且输出的顺序不正确。我正在阅读Lat's Longs的CSV并拥有高级帐户API密钥。如果可能的话,或许可以一次完成整个文件(大约5,500个条目)。

var employee_data = data.split(/\r?\n|\r/);//Splits rows
var table_data = '<table class="table table-bordered table-striped">';
var item=0;
var long;
var lat;
var long2;
var lat2;
var loc1;
var loc2;
var flat;
var flong;
var flat2;
var flong2;
var transport;
var id;
var tcount=0;
for(var count = 0; count<employee_data.length; count++){
    var cell_data = employee_data[count].split(",");
    for(var cell_count=0; cell_count<cell_data.length; cell_count++){
        if(item===0){
            id=cell_data[cell_count];
        }
        else if(item===1){
            lat=cell_data[cell_count];
            flat = parseFloat(lat);     
        }
        else if (item===2){
            long=cell_data[cell_count];
            flong = parseFloat(long);
        }
        else if(item===4){
            lat2=cell_data[cell_count];
            flat2=parseFloat(lat2);
        }
        else if(item===5){
            long2=cell_data[cell_count];
            flong2=parseFloat(long2);
        }
        item++;
        if(item===6){

            loc1 = {lat:flat, lng:flong};
            loc2 = {lat:flat2, lng:flong2};
            if(tcount<100){
                calculateTime(loc1,loc2,id);
            }
            tcount++;
            item=0;
        }
    }
}
function calculateTime(x,y,tcount){         
    var location1 = [x];
    var location2 = [y];
    var service = new google.maps.DistanceMatrixService;
    service.getDistanceMatrix({
        origins: location1,
        destinations:location2,
        travelMode: 'DRIVING',
    }, callback);       
}
function callback(response, status) {
    try{
       if (status == 'OK') {          
           var duration;
           var distance;
           var from;
           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];
                 distance = element.distance.text;
                 duration = element.duration.text;
                 from = origins[i];
                 var to = destinations[j];
             }
         }
         console.log(duration);         
     }
    }
    catch(error){
        console.log('error caught');
    }
}

0 个答案:

没有答案