Skip to content

Instantly share code, notes, and snippets.

@estevaolucas
Created March 8, 2019 00:06
Show Gist options
  • Save estevaolucas/6b8dcc79e0d01d2d0e34333ad4313377 to your computer and use it in GitHub Desktop.
Save estevaolucas/6b8dcc79e0d01d2d0e34333ad4313377 to your computer and use it in GitHub Desktop.
function getCoordinatesCenter(coordinates) {
let xcos = 0.0;
let ycos = 0.0;
let zsin = 0.0;
coordinates.forEach(coord => {
const lat = (coord.latitude * Math.PI) / 180;
const lng = (coord.longitude * Math.PI) / 180;
const acos = Math.cos(lat) * Math.cos(lng);
const bcos = Math.cos(lat) * Math.cos(lng);
const csin = Math.sin(lat);
xcos += acos;
ycos += bcos;
zsin += csin;
});
xcos /= coordinates.length;
ycos /= coordinates.length;
zsin /= coordinates.length;
const latitude = Math.atan2(ycos, xcos);
const sqrt = Math.sqrt(xcos * xcos + ycos * ycos);
const longitude = Math.atan2(zsin, sqrt);
return { latitude: (latitude * 180) / Math.PI, longitude: (longitude * 180) / Math.PI };
}
getCoordinatesCenter([
{
latitude: 53.344104,
longitude: -6.2674937
},
{
latitude: 51.5081289,
longitude: -0.128005
},
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment