由两个纬度和经度之间的道路距离从头开始计算



所以,我是react的新手。我正试图在react中开发一个应用程序,其中我有一个多个对象的数组,每个对象中包含不同的纬度和经度。我想通过使用谷歌API或任何类似的东西来计算两个纬度和经度之间的道路距离。我不想使用Haversine公式。

您可以使用地图JavaScript API的远程矩阵服务。

首先,您需要确保在代码中加载MapsJavaScript脚本标记。加载脚本后,您可以调用距离矩阵服务,并将数组中的第一个坐标作为原点数组,然后将第二个坐标作为目标数组。我提到了原点数组和目的地数组,因为距离矩阵服务的originsdestinations参数需要一个或多个坐标的数组。我还使用状态来显示DOM中的值。请参阅下面的示例代码和代码片段。请使用您的API密钥使代码工作

import React, { Component } from "react";
class Map extends Component {
constructor(props) {
super(props);
this.state = {
originLat: null,
originLng: null,
destLat: null,
destLng: null,
distance: null
};
this.onScriptLoad = this.onScriptLoad.bind(this);
}
onScriptLoad() {
let coordsArray = [
{ lat: 41.0082, lng: 28.9784 },
{ lat: 41.1082, lng: 28.9784 }
];
this.setState({
originLat: coordsArray[0].lat,
originLng: coordsArray[0].lng,
destLat: coordsArray[0].lat,
destLng: coordsArray[0].lng
});
let service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [{ lat: this.state.originLat, lng: this.state.originLng }],
destinations: [{ lat: this.state.destLat, lng: this.state.destLng }],
travelMode: "DRIVING"
},
(response, status) => {
if (status !== "OK") {
alert("Error was: " + status);
} else {
this.setState({
distance: response.rows[0].elements[0].distance.text
});
}
}
);
}
componentDidMount() {
if (!window.google) {
var s = document.createElement("script");
s.type = "text/javascript";
s.src = `https://maps.google.com/maps/api/js?key=YOUR_API_KEY`;
var x = document.getElementsByTagName("script")[0];
x.parentNode.insertBefore(s, x);
// Below is important.
//We cannot access google.maps until it's finished loading
s.addEventListener("load", e => {
this.onScriptLoad();
});
} else {
this.onScriptLoad();
}
}
render() {
return (
<div style={{ width: 500, height: 500 }} id={this.props.id}>
<label>
Origin:({this.state.originLat},{this.state.originLng})
</label>
<br />
<label>
Destination:({this.state.destLat},{this.state.destLng})
</label>
<br />
<label>Distance:{this.state.distance}</label>
</div>
);
}
}
export default Map;

最新更新