JavaScript 根据经纬度得出中心点的经纬度
程序员文章站
2024-03-24 12:24:16
...
JavaScript 根据经纬度得出中心点的经纬度
/**
* 地点坐标计算中心点
* @param geoCoordinateList {Array<Array<Object>>} [[{lat, lng}]]
* @return { Object } {lat lng}
*/
getCenterPoint(geoCoordinateList) {
const geoCoordinateListFlat = geoCoordinateList.reduce((s, v) => {
return (s = s.concat(v))
}, [])
const total = geoCoordinateListFlat.length
let X = 0
let Y = 0
let Z = 0
for (const g of geoCoordinateListFlat) {
const lat = g.lat * Math.PI / 180
const lon = g.lng * Math.PI / 180
const x = Math.cos(lat) * Math.cos(lon)
const y = Math.cos(lat) * Math.sin(lon)
const z = Math.sin(lat)
X += x
Y += y
Z += z
}
X = X / total
Y = Y / total
Z = Z / total
const Lon = Math.atan2(Y, X)
const Hyp = Math.sqrt(X * X + Y * Y)
const Lat = Math.atan2(Z, Hyp)
return { lng: Lon * 180 / Math.PI, lat: Lat * 180 / Math.PI }
}