Skip to content

Instantly share code, notes, and snippets.

@tlhunter
Created May 17, 2017 18:00
Show Gist options
  • Select an option

  • Save tlhunter/0ea604b77775b3e7d7d25ea0f70a23eb to your computer and use it in GitHub Desktop.

Select an option

Save tlhunter/0ea604b77775b3e7d7d25ea0f70a23eb to your computer and use it in GitHub Desktop.
Calculate the center/average of multiple GeoLocation coordinates
/**
* Calculate the center/average of multiple GeoLocation coordinates
* Expects an array of objects with .latitude and .longitude properties
*
* @url http://stackoverflow.com/a/14231286/538646
*/
function averageGeolocation(coords) {
if (coords.length === 1) {
return coords[0];
}
let x = 0.0;
let y = 0.0;
let z = 0.0;
for (let coord of coords) {
let latitude = coord.latitude * Math.PI / 180;
let longitude = coord.longitude * Math.PI / 180;
x += Math.cos(latitude) * Math.cos(longitude);
y += Math.cos(latitude) * Math.sin(longitude);
z += Math.sin(latitude);
}
let total = coords.length;
x = x / total;
y = y / total;
z = z / total;
let centralLongitude = Math.atan2(y, x);
let centralSquareRoot = Math.sqrt(x * x + y * y);
let centralLatitude = Math.atan2(z, centralSquareRoot);
return {
latitude: centralLatitude * 180 / Math.PI,
longitude: centralLongitude * 180 / Math.PI
};
}
// expect ~ 37.790831, -122.407169
const sf = [{
latitude: 37.797749,
longitude: -122.412147
}, {
latitude: 37.789068,
longitude: -122.390604
}, {
latitude: 37.785269,
longitude: -122.421975
}];
console.log(averageGeolocation(sf));
// expect ~ 8.670552, -173.207864
const globe = [{ // Japan
latitude: 37.928969,
longitude: 138.979637
}, { // Nevada
latitude: 39.029788,
longitude: -119.594585
}, { // New Zealand
latitude: -39.298237,
longitude: 175.717917
}];
console.log(averageGeolocation(globe));
@dominichr1

Copy link
Copy Markdown

When I applied this to your example, I got a mean latitude: 19.21417269459288 and mean longitude: -176.73031760486452. What could I done wrong?

@dcts

dcts commented Jul 20, 2020

Copy link
Copy Markdown

@dominichr1 same here!

@seenuvasanv

Copy link
Copy Markdown

@ Here as well

@tlhunter

Copy link
Copy Markdown
Author

Consider this broken!

@AZagatti

Copy link
Copy Markdown

Work here, but the results comments is wrong

@MaximTarovik-Reg

Copy link
Copy Markdown

Don't know what everyone is talking about, works wonders!

Thank you @tlhunter.

@tlhunter

tlhunter commented Oct 26, 2021

Copy link
Copy Markdown
Author

The bug might only happen in certain scenarios, like comparing points across the Prime Meridian or Equator.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment