Google maps 谷歌地图api v3按州计算里程

Google maps 谷歌地图api v3按州计算里程,google-maps,google-maps-api-3,google-distancematrix-api,Google Maps,Google Maps Api 3,Google Distancematrix Api,我正在寻找一种方法,使用谷歌地图API v3,根据路线的起点、航路点和目的地,按美国各州计算里程 我曾尝试使用谷歌距离矩阵API,但这是计算两个点之间的距离,这很好,但我需要对每个州的行驶英里数进行细分。出于税务目的(IFTA报告运输) 我在谷歌上做了很多搜索,查阅了文档,但我没有看到任何计算每个州的里程数的东西 我知道如何使用谷歌地图,我知道这是可能的,因为我在一个视频中看到了它。没有代码可以显示,因为我不知道如何做。有什么想法吗 我发现了一些有用的链接: 如何使用Google Map API

我正在寻找一种方法,使用谷歌地图API v3,根据路线的起点、航路点和目的地,按美国各州计算里程

我曾尝试使用谷歌距离矩阵API,但这是计算两个点之间的距离,这很好,但我需要对每个州的行驶英里数进行细分。出于税务目的(IFTA报告运输)

我在谷歌上做了很多搜索,查阅了文档,但我没有看到任何计算每个州的里程数的东西

我知道如何使用谷歌地图,我知道这是可能的,因为我在一个视频中看到了它。没有代码可以显示,因为我不知道如何做。有什么想法吗

我发现了一些有用的链接:

如何使用Google Map API V3动态绘制路线并计算路线时间和距离


如何使用Google Maps API构建测距仪下面是一个使用Google Maps Javascript API的全功能实现。您只需添加自己的Maps API密钥。正如上面提到的帖子所述,谷歌地图以渐进的速度限制请求,因此,路由越长,计算所需的时间就越长。从纽黑文CT到新泽西州/宾夕法尼亚州边境的路线大概需要5分钟。从纽黑文CT到洛杉矶的旅程需要45分钟。另一个注意事项是:有几个州的边界穿过水体。谷歌认为这些文件不在任何州,因此报告未定义为州名。在大多数情况下,这些路段显然只有十分之几英里,但我觉得我应该提及它,只是为了澄清发生这种情况时会发生什么

更新:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

<script src="https://maps.googleapis.com/maps/api/js?key=<YOUR-KEY-HERE>"></script>
<div id="map" style="height:400px"></div>
<div id="status"></div>
<div id="results" style="height:400px"><b>Results:</b></div>

<script>

var directionsRequest = {
  origin: "New York, NY", //default
  destination: "Los Angeles, LA", //default
  optimizeWaypoints: true,
  provideRouteAlternatives: false,
  travelMode: google.maps.TravelMode.DRIVING,
  drivingOptions: {
    departureTime: new Date(),
    trafficModel: google.maps.TrafficModel.PESSIMISTIC
  }
};

directionsRequest.origin = prompt("Enter your starting address");
directionsRequest.destination = prompt("Enter your destination address");
var starttime = new Date();

var geocoder  = new google.maps.Geocoder();
var startState;
var currentState;
var routeData;
var index = 0;
var stateChangeSteps = [];
var borderLatLngs = {};
var startLatLng;
var endLatLng;

directionsService = new google.maps.DirectionsService();
directionsService.route(directionsRequest, init);

function init(data){
    routeData = data;
    displayRoute();
    startLatLng = data.routes[0].legs[0].start_location;
    endLatLng = data.routes[0].legs[0].end_location;
    geocoder.geocode({location:data.routes[0].legs[0].start_location}, assignInitialState)

}

function assignInitialState(data){
    startState = getState(data);
    currentState = startState;
    compileStates(routeData);
}

function getState(data){
    for (var i = 0; i < data.length; i++) {
        if (data[i].types[0] === "administrative_area_level_1") {
            var state = data[i].address_components[0].short_name;
        }
    }
    return state;
}

function compileStates(data, this_index){
    if(typeof(this_index) == "undefined"){
        index = 1;
        geocoder.geocode({location:data.routes[0].legs[0].steps[0].start_location}, compileStatesReceiver);
    }else{
        if(index >= data.routes[0].legs[0].steps.length){
            console.log(stateChangeSteps);
            index = 0;
            startBinarySearch();
            return;
        }
        setTimeout(function(){ 
                geocoder.geocode({location:data.routes[0].legs[0].steps[index].start_location}, compileStatesReceiver);
                $("#status").html("Indexing Step "+index+"...  ("+data.routes[0].legs[0].steps.length+" Steps Total)");
            }, 3000)
    }

}

function compileStatesReceiver(response){
      state = getState(response);
      console.log(state);
      if(state != currentState){
            currentState = state;
            stateChangeSteps.push(index-1);
      }
      index++; 
      compileStates(routeData, index);

    }



var stepIndex = 0;
var stepStates = [];
var binaryCurrentState = "";
var stepNextState;
var stepEndState;
var step;

var myLatLng = {lat:39.8282, lng:-98.5795};
var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: myLatLng
  });

function displayRoute() {
  directionsDisplay = new google.maps.DirectionsRenderer();
  directionsDisplay.setMap(map);
  directionsDisplay.setDirections(routeData);
}

var orderedLatLngs = [];
function startBinarySearch(iterating){
    if(stepIndex >= stateChangeSteps.length){
        for(step in borderLatLngs){
            for(state in borderLatLngs[step]){
                for(statename in borderLatLngs[step][state]){
                   $("#results").append("<br>Cross into "+statename+" at "+JSON.stringify(borderLatLngs[step][state][statename], null, 4));
                   orderedLatLngs.push([borderLatLngs[step][state][statename], statename]); 
                }
            }
        }
        compileMiles(true);
        return;

    }
    step = routeData.routes[0].legs[0].steps[stateChangeSteps[stepIndex]];
    console.log("Looking at step "+stateChangeSteps[stepIndex]);
    borderLatLngs[stepIndex] = {};
    if(!iterating){
        binaryCurrentState = startState;
    }
    geocoder.geocode({location:step.end_location}, 
        function(data){
            if(data === null){
                setTimeout(function(){startBinarySearch(true);}, 6000);
            }else{
                stepNextState = getState(data);
                stepEndState = stepNextState;
                binaryStage2(true);
            }
        });
}

var minIndex;
var maxIndex;
var currentIndex;
function binaryStage2(init){
    if (typeof(init) != "undefined"){   
        minIndex = 0;
        maxIndex  = step.path.length - 1;    
    }
    if((maxIndex-minIndex)<2){
        borderLatLngs[stepIndex][maxIndex]={};
        borderLatLngs[stepIndex][maxIndex][stepNextState]=step.path[maxIndex];
        var marker = new google.maps.Marker({
            position: borderLatLngs[stepIndex][maxIndex][stepNextState],
            map: map,
        });
        if(stepNextState != stepEndState){
            minIndex = maxIndex;
            maxIndex = step.path.length - 1;
            binaryCurrentState = stepNextState;
            stepNextState = stepEndState;

        }else{
            stepIndex++;
            binaryCurrentState = stepNextState;
            startBinarySearch(true);
            return;
        }
    }
    console.log("Index starts: "+minIndex+" "+maxIndex);
    console.log("current state is "+binaryCurrentState);
    console.log("next state is "+ stepNextState);
    console.log("end state is "+ stepEndState);

    currentIndex = Math.floor((minIndex+maxIndex)/2);
    setTimeout(function(){
                geocoder.geocode({location:step.path[currentIndex]}, binaryStage2Reciever);
                $("#status").html("Searching for division between "+binaryCurrentState+" and "+stepNextState+" between indexes "+minIndex+" and "+maxIndex+"...") 
            }, 3000);


}

function binaryStage2Reciever(response){
    if(response === null){
        setTimeout(binaryStage2, 6000);
    }else{
        state = getState(response)
        if(state == binaryCurrentState){
            minIndex = currentIndex +1; 
        }else{
            maxIndex = currentIndex - 1
            if(state != stepNextState){
                stepNextState = state;
            }
        }
        binaryStage2();
    }
}

var currentStartPoint;
var compileMilesIndex = 0;
var stateMiles = {};
var trueState;
function compileMiles(init){
        if(typeof(init)!= "undefined"){
            currentStartPoint = startLatLng;
            trueState = startState;    
        }
        if(compileMilesIndex == orderedLatLngs.length){
            directionsRequest.destination = endLatLng;
        }else{
            directionsRequest.destination = orderedLatLngs[compileMilesIndex][0];
        }
        directionsRequest.origin = currentStartPoint;
        currentStartPoint = directionsRequest.destination;
        directionsService.route(directionsRequest, compileMilesReciever)

}

function compileMilesReciever(data){
    if(data===null){
        setTimeout(compileMiles, 6000);
    }else{
        if(compileMilesIndex == orderedLatLngs.length){
            stateMiles[stepEndState]=data.routes[0].legs[0].distance["text"];
            $("#results").append("<br><br><b>Distances Traveled</b>");
            for(state in stateMiles){
                $("#results").append("<br>"+state+": "+stateMiles[state]);
            }
            var endtime = new Date();
            totaltime = endtime - starttime;
            $("#results").append("<br><br>Operation took "+Math.floor(totaltime/60000)+" minute(s) and "+(totaltime%60000)/1000+" second(s) to run.");
            return;
        }else{
            stateMiles[trueState]=data.routes[0].legs[0].distance["text"];
        }
        trueState = orderedLatLngs[compileMilesIndex][1];
        compileMilesIndex++;
        setTimeout(compileMiles, 3000);
    }
}




</script>

</script>

结果:
变量方向请求={
来源:“纽约州纽约市”//默认值
目的地:“洛杉矶”//默认
航路点:对,
ProviderRouteAlternatives:false,
travelMode:google.maps.travelMode.DRIVING,
驾驶选项:{
出发时间:新日期(),
流量模型:google.maps.trafficModel.悲观
}
};
directionrequest.origin=提示(“输入起始地址”);
directionrequest.destination=提示(“输入您的目的地地址”);
var starttime=新日期();
var geocoder=new google.maps.geocoder();
var startState;
无功电流状态;
var routeData;
var指数=0;
var stateChangeSteps=[];
var borderLatLngs={};
var-atlng;
var endLatLng;
directionsService=new google.maps.directionsService();
路由(directionrequest,init);
函数初始化(数据){
RoutedData=数据;
displayRoute();
STARTATLNG=data.routes[0]。支腿[0]。起始位置;
endLatLng=data.routes[0]。支腿[0]。结束位置;
geocoder.geocode({location:data.routes[0]。legs[0]。start_location},assignInitialState)
}
函数赋值初始状态(数据){
startState=getState(数据);
当前状态=开始状态;
不动产(routeData);
}
函数getState(数据){
对于(变量i=0;i=data.routes[0]。legs[0]。steps.length){
console.log(stateChangeSteps);
指数=0;
startBinarySearch();
返回;
}
setTimeout(函数(){
geocoder.geocode({location:data.routes[0].legs[0].steps[index].start_location},compileStateSeceiver);
$(“#status”).html(“索引步骤”+index+”…(“+data.routes[0]。legs[0]。steps.length+“steps Total”);
}, 3000)
}
}
函数CompileStatestReceiver(响应){
state=getState(响应);
console.log(状态);
如果(状态!=当前状态){
当前状态=状态;
stateChangeSteps.push(索引-1);
}
索引++;
房地产(路线数据、索引);
}
var指数=0;
var阶跃状态=[];
var binaryCurrentState=“”;
var stepNextState;
var阶跃状态;
var阶跃;
var Mylatng={lat:39.8282,lng:-98.5795};
var map=new google.maps.map(document.getElementById('map'){
缩放:4,
中心:myLatLng
});
函数displayRoute(){
directionsDisplay=new google.maps.DirectionsRenderer();
方向显示.setMap(地图);
方向显示。设置方向(路由数据);
}
var orderedLatLngs=[];
函数startBinarySearch(迭代){
if(stepIndex>=stateChangeSteps.length){
用于(步进边框){
for(在borderLatLngs[步骤]中的状态){
对于(borderLatLngs[步骤][状态]中的statename){
$(“#results”).append(
在“+JSON.stringify(borderLatLngs[step][state][statename],null,4)”处插入“+statename+”; orderedLatLngs.push([borderLatLngs[step][state][statename],statename]); } } } 埃米尔斯(真); 返回; } 步骤=路由数据。路由[0]。支腿[0]。步骤[stateChangeSteps[stepIndex]; log(“查看步骤”+stateChangeSteps[stepIndex]); borderLatLngs[stepIndex]={}; 如果(!迭代){ binaryCurrentState=startState; } geocoder.geocode({location:step.end_location}, 功能(数据){ 如果(数据===null){ setTimeout(函数(){startBinarySearch(true);},6000); }否则{ stepNextState=getState(数据); stepEndState=stepNextState; 二进制阶段2(真); } }); } var minIndex; var最大指数; var电流指数; 函数binaryStage2(init){ if(typeof(init)!=“未定义”){ minIndex=0; maxIndex=step.path.length-1;