Created
February 7, 2019 07:51
-
-
Save karl-gustav/887370d670f608470d78da09c5f52ddd to your computer and use it in GitHub Desktop.
Get center of a list of 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 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