Skip to content

Instantly share code, notes, and snippets.

@aapis
Last active August 29, 2015 14:02
Show Gist options
  • Save aapis/7e553457b302d4eac66d to your computer and use it in GitHub Desktop.
Save aapis/7e553457b302d4eac66d to your computer and use it in GitHub Desktop.
Determine the center point of multiple geographical locations in JS
var Map = function(){}
/**
* Calculate the Lat/Lng centerpoint of several Google Maps markers
* Based on: https://gist.github.com/amites/3718961
* @param {array} latlngpoints
* @return {Object}
*/
Map.prototype.calculateCenterPoint = function(latlngpoints){
var x = 0,
y = 0,
z = 0,
len = latlngpoints.length;
for(var i = 0; i < latlngpoints.length; i++){
var lat = latlngpoints[i].lat,
lng = latlngpoints[i].lng;
x += Math.cos(lat) * Math.cos(lng);
y += Math.cos(lat) * Math.sin(lng);
z += Math.sin(lat);
}
x = (x / len);
y = (y / len);
z = (z / len);
var output = {
lat: toDegrees(Math.atan2(z, Math.sqrt(x * x + y * y))),
lng: toDegrees(Math.atan2(y, x))
};
return output;
};
/**
* Convert a radian value to degrees
* @param {float} fromRadian
* @return {float)
*/
function toDegrees(fromRadian){
return fromRadian / (Math.PI / 180);
}
/**
* Convery a degree value to a radian
* @param {float} fromDegree
* @return {float}
*/
function toRadians(fromDegree){
return fromDegree * (Math.PI / 180);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment