Skip to content

Instantly share code, notes, and snippets.

@karl-gustav
Created February 7, 2019 07:51
Show Gist options
  • Save karl-gustav/887370d670f608470d78da09c5f52ddd to your computer and use it in GitHub Desktop.
Save karl-gustav/887370d670f608470d78da09c5f52ddd to your computer and use it in GitHub Desktop.
Get center of a list of coordinates
function centerCoordinates(coordinates) {
if (coordinates.length === 0) {
return coordinates;
}
let x, y, z;
x = y = z = 0;
coordinates.forEach(coordinate => {
const latitude = (coordinate[0] * Math.PI) / 180;
const longitude = (coordinate[1] * Math.PI) / 180;
x += Math.cos(latitude) * Math.cos(longitude);
y += Math.cos(latitude) * Math.sin(longitude);
z += Math.sin(latitude);
});
x = x / coordinates.length;
y = y / coordinates.length;
z = z / coordinates.length;
const centralLongitude = Math.atan2(y, x);
const centralSquareRoot = Math.sqrt(x * x + y * y);
const centralLatitude = Math.atan2(z, centralSquareRoot);
return [
(centralLatitude * 180) / Math.PI,
(centralLongitude * 180) / Math.PI,
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment