[记录]根据经纬度计算两点间的距离

下面是一个根据经纬度计算两点间距离的方法记录:

function rad(d){
  return d * Math.PI / 180.0;
}

module.exports = function getDistance(addr1,addr2,autoFormat = false){
  const EARTH_RADIUS = 6378137;
  const lon1 = addr1.lon;
  const lat1 = addr1.lat;
  const lon2 = addr2.lon;
  const lat2 = addr2.lat;

  let radLon1 = rad(lon1)
  let radLon2 = rad(lon2)
  let radLat1 = rad(lat1)
  let radLat2 = rad(lat2)

  if(radLat1 < 0){
    radLat1 = Math.PI / 2 + Math.abs(radLat1);// south  
  }
  if(radLat1 > 0){
    radLat1 = Math.PI / 2 - Math.abs(radLat1);// north  
  }
  if(radLon1 < 0){
    radLon1 = Math.PI * 2 - Math.abs(radLon1);// west  
  }
  if(radLat2 < 0){
    radLat2 = Math.PI / 2 + Math.abs(radLat2);// south  
  }
  if(radLat2 > 0){
    radLat2 = Math.PI / 2 - Math.abs(radLat2);// north  
  }
  if(radLon2 < 0){
    radLon2 = Math.PI * 2 - Math.abs(radLon2);// west  
  }

  const x1 = EARTH_RADIUS * Math.cos(radLon1) * Math.sin(radLat1);
  const y1 = EARTH_RADIUS * Math.sin(radLon1) * Math.sin(radLat1);
  const z1 = EARTH_RADIUS * Math.cos(radLat1);

  const x2 = EARTH_RADIUS * Math.cos(radLon2) * Math.sin(radLat2);
  const y2 = EARTH_RADIUS * Math.sin(radLon2) * Math.sin(radLat2);
  const z2 = EARTH_RADIUS * Math.cos(radLat2);

  const d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) + (z1 - z2) * (z1 - z2));
  //余弦定理求夹角  
  const theta = Math.acos((EARTH_RADIUS * EARTH_RADIUS + EARTH_RADIUS * EARTH_RADIUS - d * d) / (2 * EARTH_RADIUS * EARTH_RADIUS));
  const dist = (theta * EARTH_RADIUS);
  if(autoFormat){
    if(dist < 1000){
      return dist + "m"
    }else{
      return dist / 1000 + "km"
    }
  }
  return dist;
}

其中,getDistance 接收两个位置信息作为参数,以及一个是否自动格式化的可选参数,当此参数传为 true 时,会对返回值进行转换。

完。

你可能感兴趣的:([记录]根据经纬度计算两点间的距离)