我想从地理坐标集合中计算距离。我已将其转换为GPX文件,并且可以在HERE Maps中使用它来计算距离。
现在,我想根据客户要求在Google Maps中使用它。 Google Maps中是否有任何选项可以接受GPX文件和返回距离?我看过distancematrix选项,并相信这是不同的格式。
谢谢,
这里有一些部分。基于Google Maps docs的计算。
注意,如果只需要计算距离,甚至都不需要google maps api。计算仅基于坐标。
GPX基本上是xml和html。因此,在使用window.DOMParser().parseFromString(str, "text/xml"));
解析文件的内容之后,可以使用DOM API(例如querySelector
,querySelectorAll
等)来检索所有trkpt
元素并提取其lat
和lon
值。
const coords = Array.from(xml.querySelectorAll("trkpt")).map(
element =>
new google.maps.LatLng(
Number(element.getAttribute("lat")),
Number(element.getAttribute("lon"))
)
);
我使用了google.maps.LatLng
,但如果不需要它与地图进行交互,则可以将其存储在一个普通对象中。
迭代坐标数组并从一个点到另一个点进行测量。
function haversine_distance(coord1, coord2) {
const R = 3958.8; // Radius of the Earth in miles
const rlat1 = coord1.lat() * (Math.PI/180); // Convert degrees to radians
const rlat2 = coord2.lat() * (Math.PI/180); // Convert degrees to radians
const difflat = rlat2-rlat1; // Radian difference (latitudes)
const difflon = (coord2.lng()-coord1.lng()) * (Math.PI/180); // Radian difference (longitudes)
const d = 2 * R * Math.asin(Math.sqrt(Math.sin(difflat/2)*Math.sin(difflat/2)+Math.cos(rlat1)*Math.cos(rlat2)*Math.sin(difflon/2)*Math.sin(difflon/2)));
return d;
}
然后您可以使用该函数来构建距离数组
const distances = coords.reduce((old, ne, index, original) => {
if (index > 0) {
old.push(haversine_distance(ne, original[index - 1]));
}
return old;
}, []);
https://codesandbox.io/s/elegant-turing-tvhu1?file=/index.html