用JavaScript计算两点经纬度距离
2019-05-17 本文已影响0人
小小的开发人员
计算地球表面两点间的距离大概有两种办法。
第一种是默认地球是一个光滑的球面,然后计算任意两点间的距离,这个距离叫做大圆距离(The Great Circle Distance):
var EARTH_RADIUS = 6378137.0; //单位m
var PI = Math.PI;
function getRad(d){
return d*PI/180.0;
}
function getGreatCircleDistance(lat1,lng1,lat2,lng2){
var radLat1 = getRad(lat1);
var radLat2 = getRad(lat2);
var a = radLat1 - radLat2;
var b = getRad(lng1) - getRad(lng2);
var s = 2*Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) + Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
s = s*EARTH_RADIUS;
s = Math.round(s*10000)/10000.0;
return s;
}
地球并不是一个真正的圆球体,而是椭球,有了下面的公式:
/** 计算两经纬度之间的距离,单位是m
* approx distance between two points on earth ellipsoid
*/
function getFlatternDistance (lat1, lng1, lat2, lng2) {
const PI = Math.PI
const EARTH_RADIUS = 6378137.0
function getRad (d) {
return d * PI / 180.0
}
let f = getRad((lat1 + lat2) / 2)
let g = getRad((lat1 - lat2) / 2)
let l = getRad((lng1 - lng2) / 2)
let sg = Math.sin(g)
let sl = Math.sin(l)
let sf = Math.sin(f)
let s, c, w, r, d, h1, h2
let a = EARTH_RADIUS
let fl = 1 / 298.257
sg = sg * sg
sl = sl * sl
sf = sf * sf
s = sg * (1 - sl) + (1 - sf) * sl
c = (1 - sg) * (1 - sl) + sf * sl
w = Math.atan(Math.sqrt(s / c))
r = Math.sqrt(s * c) / w
d = 2 * w * a
h1 = (3 * r - 1) / 2 / c
h2 = (3 * r + 1) / 2 / s
return d * (1 + fl * (h1 * sf * (1 - sg) - h2 * (1 - sf) * sg))
}
精度比较
提供一个在线计算经纬度的网站:http://www.hhlink.com/%E7%BB%8F%E7%BA%AC%E5%BA%A6/
let EARTH_RADIUS = 6378137.0; //单位m
let PI = Math.PI;
function getRad(d){
return d*PI/180.0;
}
function getGreatCircleDistance(lat1,lng1,lat2,lng2){
let radLat1 = getRad(lat1);
let radLat2 = getRad(lat2);
let a = radLat1 - radLat2;
let b = getRad(lng1) - getRad(lng2);
let s = 2*Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) + Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
s = s*EARTH_RADIUS;
s = Math.round(s*10000)/10000.0;
return s;
}
/** 计算两经纬度之间的距离,单位是m
* approx distance between two points on earth ellipsoid
*/
function getFlatternDistance (lat1, lng1, lat2, lng2) {
const PI = Math.PI
const EARTH_RADIUS = 6378137.0
function getRad (d) {
return d * PI / 180.0
}
let f = getRad((lat1 + lat2) / 2)
let g = getRad((lat1 - lat2) / 2)
let l = getRad((lng1 - lng2) / 2)
let sg = Math.sin(g)
let sl = Math.sin(l)
let sf = Math.sin(f)
let s, c, w, r, d, h1, h2
let a = EARTH_RADIUS
let fl = 1 / 298.257
sg = sg * sg
sl = sl * sl
sf = sf * sf
s = sg * (1 - sl) + (1 - sf) * sl
c = (1 - sg) * (1 - sl) + sf * sl
w = Math.atan(Math.sqrt(s / c))
r = Math.sqrt(s * c) / w
d = 2 * w * a
h1 = (3 * r - 1) / 2 / c
h2 = (3 * r + 1) / 2 / s
return d * (1 + fl * (h1 * sf * (1 - sg) - h2 * (1 - sf) * sg))
}
let result1 = getGreatCircleDistance(30.1234, 140.1234, 30.3456, 140.3456)
let result2 = getFlatternDistance(30.1234, 140.1234, 30.3456, 140.3456)
console.log(result1) // 32688.3298
console.log(result2) // 32622.43244078783
可以看到两种方法计算出的距离还是比较接近的,做项目时我也跟后台开发确认过,他的计算结果与第二种计算方法吻合度好。