Last active
January 19, 2021 15:30
-
-
Save johannesjo/dd11f1f415d85e9c62191e816f7956e5 to your computer and use it in GitHub Desktop.
Get the center of two or more geo coordinates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getGeoCenter(data) { | |
const coordLength = data.length; | |
let x = 0; | |
let y = 0; | |
let z = 0; | |
for (const item of data) { | |
const lat = item.lat * Math.PI / 180; | |
const lon = item.lng * Math.PI / 180; | |
x += Math.cos(lat) * Math.cos(lon); | |
y += Math.cos(lat) * Math.sin(lon); | |
z += Math.sin(lat); | |
} | |
x /= coordLength; | |
y /= coordLength; | |
z /= coordLength; | |
const lonResult = Math.atan2(y, x); | |
const hyp = Math.sqrt(x * x + y * y); | |
const latResult = Math.atan2(z, hyp); | |
return { | |
lat: (latResult * 180 / Math.PI), | |
lng: (lonResult * 180 / Math.PI), | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment