我的路线来自Google Directions API,它的起点和终点之间有很多点。如果您从某一点开始并按照该路线行驶X分钟,有什么方法可以弄清楚您的位置?
基本上,有什么方法可以获取一段具有特定行程时间长度的路线,而不仅仅是距离吗?
最佳答案
假设(根据您的问题,我假设)您具有有效的google.maps.DirectionsResult对象。
该对象具有routes
属性,该属性是google.maps.DirectionsRoute类型的对象。通常,您只有一条路线。所述路由将具有legs
属性,该属性是google.maps.DirectionsLeg的数组。
此时,您可以说您有一个变量legs
,它是
var legs = myDirectionsResult.routes[0].legs;
可以有一条或多条腿(根据您的航路点)。每条支路都有一个
steps
属性,该属性是google.maps.DirectionsStep的数组。每个步骤都具有诸如
start_location
,end_location
,duration
和distance
的属性。因此,最后,您可以按照以下步骤获得路线的步骤:
var steps = myDirectionsResult
.routes[0]
.legs
.reduce(function(accum,leg) {
accum=accum.concat(leg.steps);
return accum;
},[]);
现在,您可以遍历这些步骤,直到达到时间限制:
var currentStep,
duration,
start_location,
end_location,
timeSpent,
totalSteps = steps.length,
timelimit = 900; // seconds.
for(var i=0; i < totalSteps; i++) {
currentStep = steps[i];
duration = currentStep.duration.value;
start_location= currentStep.start_location;
end_location = currentStep.end_location;
if(timeSpent + duration > timelimit) {
break;
}
timeSpent = timeSpent + duration;
}
因此,让我们分解一下。您有一系列步骤和时间限制。您遍历这些步骤。在每个步骤的开始,您检查是否完成此步骤将使您的旅行时间超出时间限制,在这种情况下,您会中断循环。否则,您可以将步骤的持续时间添加到所花费的时间,然后继续进行下一个。
由于您开始声明时限为900秒,因此最终将花费850秒,而当前步骤的持续时间为100秒,因此您无法完成此操作。您已经设置了此步骤的开始和结束位置,因此您可以打破循环,并且知道可以到达这两个位置之间的某个位置,直到完成时间限制。
在这种情况下,该步骤的持续时间为100秒,而您仅剩50秒,因此您知道已经到达当前步骤的开始和结束位置之间的中点。您需要在这些位置之间进行插值才能知道最终坐标。如果您认为对于较小的距离,坐标之间的差异的行为就像在笛卡尔平面上的行为,则可以手动执行此操作。 (请参见Small Angle Aproximation),但您也可以使用Google地图的几何库(请参见google.maps.geometry.spherical.interpolate)