使用gpx文件计算与Google地图的距离

问题描述 投票:2回答:1

我想从地理坐标集合中计算距离。我已将其转换为GPX文件,并且可以在HERE Maps中使用它来计算距离。

现在,我想根据客户要求在Google Maps中使用它。 Google Maps中是否有任何选项可以接受GPX文件和返回距离?我看过distancematrix选项,并相信这是不同的格式。

谢谢,

javascript google-maps distance
1个回答
0
投票

这里有一些部分。基于Google Maps docs的计算。

注意,如果只需要计算距离,甚至都不需要google maps api。计算仅基于坐标。

解析GPX文件

GPX基本上是xml和html。因此,在使用window.DOMParser().parseFromString(str, "text/xml"));解析文件的内容之后,可以使用DOM API(例如querySelectorquerySelectorAll等)来检索所有trkpt元素并提取其latlon值。

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

© www.soinside.com 2019 - 2024. All rights reserved.