谷歌地图api v3按国家计算里程数 [英] Google maps api v3 calculate mileage by state

查看:98
本文介绍了谷歌地图api v3按国家计算里程数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法,根据使用Google Maps API v3的路线的出发点,航点和目的地,美国各州计算里程数。



我有尝试使用谷歌距离矩阵API,但这是计算两点之间的距离,这是好的,但我需要为每个国家旅行的英里分解。出于税收目的(IFTA报告运输)。



我做了大量的Google搜索并查看了文档,但我没有看到任何计算每英里的里程数州。



我知道如何使用谷歌地图,我知道这是可能的,因为我在一个视频中看到它。没有我能展示的代码,因为我不知道如何去做。任何想法?



我找到的有用链接:



如何绘制路线并计算路线时间和距离使用谷歌地图API V3飞行 http://www.c-sharpcorner.com/UploadFile/8911c4/how-to-draw-routes-and-calculate-route-time-and-distance-on/

如何使用Google Maps API构建测距仪 http://www.1stwebdesigner.com/distance-finder-google-maps-api/

解决方案

以下是使用Google Maps JavaScript API的全功能实施。您需要添加的是您自己的Maps API密钥。正如上面提到的帖子所指出的那样,Google Maps以渐近速度限制请求,因此路线越长,计算时间就越长。为了提供一个球场,从纽黑文CT到NJ / PA边界的路线大约需要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 =mapstyle =height:400px>< / div>
< div id =status>< / div>
< div id =resultsstyle =height:400px>< b>结果:< / 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 =提示(输入您的起始地址);
directionsRequest.destination =提示(输入您的目的地址);
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);

函数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)



函数assignInitialState(data) {
startState = getState(data);
currentState = startState;
compileStates(routeData); (数据){
}

函数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;
}
}
返回状态;


函数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));




函数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 = [];
函数startBinarySearch(迭代){
if(stepIndex> = stateChangeSteps.length){
(borderLatLngs中的步骤){
for(state in borderLatLngs [step]){
for borderLatLngs [state] [state]){
$(#results)。append(< br> Cross在+ 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(查看步骤+ 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;
函数binaryStage2(init){
if(typeof(init)!=undefined){
minIndex = 0;
maxIndex = step.path.length - 1; ((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(当前状态是+ 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在+ binaryCurrentState +和+ stepNextState +之间的索引+ minIndex +和+ 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;
函数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)



函数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>已完成的距离< / b>);
for(stateMiles){
$(#results)。append(< br>+ state +:+ stateMiles [state]);
}
var endtime = new Date();
totaltime = endtime - starttime;
$(#results)。append(< br>< br> Operation taken+ Math.floor(totaltime / 60000)+minute(s)and+(totaltime%60000)/ 1000+秒才能运行。);
return;
} else {
stateMiles [trueState] = data.routes [0] .legs [0] .distance [text];
}
trueState = orderedLatLngs [compileMilesIndex] [1];
compileMilesIndex ++;
setTimeout(compileMiles,3000);
}
}




< / script>

< / script>


I'm searching for a way to calculate mileage by US State based on an origin, waypoints and destination of a route using Google Maps API v3.

I have tried using Googles Distance Matrix API but this it is calculating the distance between 2 points, which is good, but I need the break down for miles traveled for each State. For taxes purposes (IFTA reports for transportation).

I've done a lot of googling and looked through the documentation but I'm not seeing anything that calculate the mileage per State.

I know how to use Google maps and I know this is possible since I saw it on one video. There is no code I can show because I have no idea how to do it. Any thoughts?

Useful links I have found:

How to Draw Routes and Calculate Route Time and Distance on the Fly Using Google Map API V3 http://www.c-sharpcorner.com/UploadFile/8911c4/how-to-draw-routes-and-calculate-route-time-and-distance-on/

How to Build a Distance Finder with Google Maps API http://www.1stwebdesigner.com/distance-finder-google-maps-api/

解决方案

Below is a fully functional implementation that uses the Google Maps Javascript API. All you need to add is your own Maps API Key. As noted in the posts referenced above, Google Maps throttles requests at an asymptotic rate, and thus, the longer the route, the longer it will take to calculate. To give a ballpark, a route from New Haven CT to the NJ/PA border takes approximately 5 minutes. A trip from New Haven CT to Los Angeles takes 45 minutes to index. One other note: There are a few state borders that run through bodies of water. Google considers these to be not located in any state, and so reports undefined as the state name. These sections are obviously only a few tenths of a mile in most cases, but I felt I should mention it just to clarify what is going on when that happens.

UPDATED:

<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>

这篇关于谷歌地图api v3按国家计算里程数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆