Fixed the haversine formula to calculate distance between 2 points properly

This commit is contained in:
Simo Moujami 2014-12-10 16:30:07 -05:00
parent 56323ee10f
commit ed5aeb1d2d
1 changed files with 9 additions and 4 deletions

View File

@ -239,17 +239,22 @@ var EARTH_RADIUS = {
};
function geoDistance(x1, y1, x2, y2, options) {
var type = (options && options.type) || 'miles';
// Convert to radians
x1 = x1 * DEG2RAD;
y1 = y1 * DEG2RAD;
x2 = x2 * DEG2RAD;
y2 = y2 * DEG2RAD;
var a = Math.pow(Math.sin(( y2 - y1 ) / 2.0), 2);
var b = Math.pow(Math.sin(( x2 - x1 ) / 2.0), 2);
var c = Math.sqrt(a + Math.cos(y2) * Math.cos(y1) * b);
// use the haversine formula to calculate distance for any 2 points on a sphere.
// ref http://en.wikipedia.org/wiki/Haversine_formula
var haversine = function(a) {
return Math.pow(Math.sin(a / 2.0), 2)
}
var type = (options && options.type) || 'miles';
var c = Math.sqrt(haversine(x2 - x1) + Math.cos(x2) * Math.cos(x1) * haversine(y2 - y1));
return 2 * Math.asin(c) * EARTH_RADIUS[type];
}