[记录]根据经纬度计算两点间的距离
下面是一个根据经纬度计算两点间距离的方法记录:
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
时,会对返回值进行转换。完。
推荐阅读
- 20170612时间和注意力开销记录
- 【剽悍读书营成长记录】2018年我收获了什么|【剽悍读书营成长记录】2018年我收获了什么 3357-小松
- 记录iOS生成分享图片的一些问题,根据UIView生成固定尺寸的分享图片
- 课后分享记录
- 感赏15+投射
- Day5+5组+小鹿#写手账,就是记录你一生的帐
- 不知不觉,他们又长大了一点
- 运营是什么()
- 记录下有意义的事2021-05-14
- ATAN2根据xy坐标计算角度