Javascript 使用google api测量3个标记之间的距离
我使用react js,从用户输入中获取坐标。现在我想计算这些坐标之间的总距离,以英里为单位。例如 51.5035914, -0.1193578 51.5031346, -0.1193844 51.5038217,-0.1282733 从a点到b点的距离+从b点到c点的距离Javascript 使用google api测量3个标记之间的距离,javascript,reactjs,google-maps,Javascript,Reactjs,Google Maps,我使用react js,从用户输入中获取坐标。现在我想计算这些坐标之间的总距离,以英里为单位。例如 51.5035914, -0.1193578 51.5031346, -0.1193844 51.5038217,-0.1282733 从a点到b点的距离+从b点到c点的距离 PS.在上面的例子中,我只添加了3个点,但它可以是30个或更多,以计算两个坐标之间的距离,您可以使用距离度量 您应该使用以下公式: 例如,对于坐标A和坐标B,您应该能够: var a = x1 - x2; // (51.5
PS.在上面的例子中,我只添加了3个点,但它可以是30个或更多,以计算两个坐标之间的距离,您可以使用距离度量 您应该使用以下公式: 例如,对于坐标A和坐标B,您应该能够:
var a = x1 - x2; // (51.5035914) - (-0.1193578)
var b = y1 - y2; // (51.5031346) - (-0.1193844)
var distance = Math.sqrt( a*a + b*b );
因此,要计算完整距离,需要遍历坐标输入数组,始终计算数组中i
和i+1
点之间的距离,并将其添加到上一个距离和中
这方面的伪代码是:
var distance = 0;
for (var i = 0; i < distances.length; i++) {
var a = distances[i].x - distances[i].y;
var b = distances[i + 1].x - distances[i + 1].y;
distance += Math.sqrt( a*a + b*b );
}
var距离=0;
对于(变量i=0;i
我希望这有帮助
编辑:
- 我给你举了一个欧几里得距离的例子,你可以检查更多的距离,看看什么对你最有利
相同的伪代码可以应用于每个距离。如果您想获得坐标之间的距离和时间,可以使用谷歌地图平台API 为此,可以首先在一个距离矩阵请求中获取点A和点B之间的距离/持续时间,并将其存储在变量中。然后在另一个请求中获取点B和点C之间的距离/持续时间,并将其添加到同一变量中 以下是显示距离矩阵请求的代码片段:
var service = new google.maps.DistanceMatrixService;
var orig = this.state.input;
var dest = this.state.destination;
service.getDistanceMatrix({
origins: [orig],
destinations: [dest],
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, (response, status) => {
if (status !== 'OK') {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
//Loop through the elements row to get the value of duration and distance
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];
var distanceString = element.distance.text;
var durationString = element.duration.text;
//add new value to the previousValue
this.setState ({
distance: this.state.distance + parseInt(distanceString, 10)
});
console.log(this.state.distance);
this.setState ({
duration: this.state.duration + parseInt(durationString, 10)
});
console.log(this.state.duration);
}
}
}
});
var service=new google.maps.DistanceMatrixService;
var orig=this.state.input;
var dest=this.state.destination;
service.getDistanceMatrix({
起源:[原文],
目的地:[目的地],
travelMode:‘驾驶’,
unitSystem:google.maps.unitSystem.METRIC,
避免:错误,
避免收费:错误
},(响应、状态)=>{
如果(状态!='OK'){
警报(“错误为:”+状态);
}否则{
var origins=response.originAddresses;
var destinations=response.destinationaddress;
//循环遍历元素行以获取持续时间和距离的值
对于(变量i=0;i
希望这有帮助 这不应用于lat long坐标。离两极越近,情况就越糟。同样,对于长距离,你会得到扔到地球上的距离,而不是在地面上的距离。@clankill3r问题中没有指定应该测量的坐标和距离。我给出了欧几里得距离的例子。任何其他指标都可以以同样的方式应用。我编辑了我的答案并添加了更多资源。谢谢你的回答,但我需要一个在这些点之间旅行的实时时间。。它包括在交通方面花费的时间。@MohammadTasneemFaizyab请更新您的问题,然后获得更多信息,以便其他看到问题的人可以给您更好的答案。这是一个非常有用的资源: