gpt4 book ai didi

javascript - 使用 google api 测量 3 个标记之间的距离

转载 作者:行者123 更新时间:2023-11-28 10:37:22 26 4
gpt4 key购买 nike

我正在使用react js,我从用户输入中获取坐标。现在我想计算这些坐标之间的总距离(以英里为单位)。例如51.5035914,-0.119357851.5031346,-0.119384451.5038217,-0.1282733

所以从a点到b点的距离+b点到c点的距离。

PS。在上面的例子中我只添加了 3 个点,但它可以是 30 或更多

最佳答案

如果您想获取坐标之间行驶的距离和持续时间,可以使用 Google Maps Platform API 的 Distance Matrix 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);
}
}
}
});

希望这有帮助!

关于javascript - 使用 google api 测量 3 个标记之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59247327/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com