Skip to content

Instantly share code, notes, and snippets.

@fnk0
Last active October 11, 2015 21:20
Show Gist options
  • Select an option

  • Save fnk0/744f6b40af44c8746c21 to your computer and use it in GitHub Desktop.

Select an option

Save fnk0/744f6b40af44c8746c21 to your computer and use it in GitHub Desktop.
Angular factory that calculates the best set of coordinates to center a set of coordiantes in a map
app.factory('calculateCenter', function($window) {
var coordinates = [];
return function(data) {
var num_coords = data.length;
var X = 0.0;
var Y = 0.0;
var Z = 0.0;
for(var i = 0; i < num_coords; i++) {
if(data[i].latitude == 0 && data[i].longitude == 0) continue;
var lat = data[i].latitude * Math.PI / 180;
var lon = data[i].longitude * Math.PI / 180;
var a = Math.cos(lat) * Math.cos(lon);
var b = Math.cos(lat) * Math.sin(lon);
var c = Math.sin(lat);
X += a;
Y += b;
Z += c;
}
X /= num_coords;
Y /= num_coords;
Z /= num_coords;
lon = Math.atan2(Y, X);
var hyp = Math.sqrt(X * X + Y * Y);
lat = Math.atan2(Z, hyp);
coordinates.push(lat * 180 / Math.PI);
coordinates.push(lon * 180 / Math.PI);
return coordinates;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment