Skip to content

Instantly share code, notes, and snippets.

@johannesjo
Last active January 19, 2021 15:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johannesjo/dd11f1f415d85e9c62191e816f7956e5 to your computer and use it in GitHub Desktop.
Save johannesjo/dd11f1f415d85e9c62191e816f7956e5 to your computer and use it in GitHub Desktop.
Get the center of two or more geo coordinates
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