计算地球上两点之间距离

发布时间 2023-10-08 14:14:09作者: _clai
function getDistance(_current, _building, showKM = false) {
  let current = JSON.parse(JSON.stringify(_current)),
    building = JSON.parse(JSON.stringify(_building));
  let a,
    b,
    R = 6378137.0; // earth radius (unit: m)
  current.lat = (current.lat * Math.PI) / 180.0;
  building.lat = (building.lat * Math.PI) / 180.0;

  a = current.lat - building.lat; // lat

  b = ((current.lng - building.lng) * Math.PI) / 180.0;

  let d, sa2, sb2;

  sa2 = Math.sin(a / 2.0);
  sb2 = Math.sin(b / 2.0);
  d =
    2 *
    R *
    Math.asin(Math.sqrt(sa2 * sa2 + Math.cos(current.lat) * Math.cos(building.lat) * sb2 * sb2));
  d = Math.round(d * 10000) / 10000;
  d = showKM ? d / 1000 : d;
  return d.toFixed(2); // unit: m
}

  • AI代码解释

这段代码是一个用于计算地球上两点之间距离的函数,该函数接受三个参数:_current 表示当前位置的经纬度,_building 表示目标位置的经纬度,showKM 用于控制返回值的单位是否为千米,默认为 false。

具体来说,该函数的计算过程如下:

将 _current 和 _building 对象中的经纬度(以度为单位)转换为弧度并存储在新的变量 current 和 building 中。

let current = JSON.parse(JSON.stringify(_current)),
  building = JSON.parse(JSON.stringify(_building));
current.lat = (current.lat * Math.PI) / 180.0;
building.lat = (building.lat * Math.PI) / 180.0;

计算两点之间的经度和纬度的差值,并将纬度差值存储在变量 a 中,经度差值存储在变量 b 中。

a = current.lat - building.lat; // lat
b = ((current.lng - building.lng) * Math.PI) / 180.0;

根据海伦公式(Haversine formula)计算两点之间的距离(以米为单位),并将结果存储在变量 d 中。其中 R 是地球的平均半径(以米为单位)。

let d, sa2, sb2;
sa2 = Math.sin(a / 2.0);
sb2 = Math.sin(b / 2.0);
d =
  2 *
  R *
  Math.asin(Math.sqrt(sa2 * sa2 + Math.cos(current.lat) * Math.cos(building.lat) * sb2 * sb2));
d = Math.round(d * 10000) / 10000;

如果 showKM 参数为 true,则将距离转换为千米并返回,否则直接返回以米为单位的距离。

d = showKM ? d / 1000 : d;
return d.toFixed(2); // unit: m

整个函数的核心部分是第三步的计算过程,它使用了海伦公式来计算两点之间的距离。海伦公式利用三角形的三个边长来计算面积,进而得到两点之间的距离。该公式在地图应用、导航系统等领域有着广泛的应用。