Skip to content

Instantly share code, notes, and snippets.

@rice2007
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rice2007/c1d3eb8caddbd5d858ec to your computer and use it in GitHub Desktop.
Save rice2007/c1d3eb8caddbd5d858ec to your computer and use it in GitHub Desktop.
/*
This script is pretty basic, but if you use it, please let me know. Thanks!
Andrew Hedges, andrew(at)hedges(dot)name
*/
var Haversine = {
Rm : 3961, // mean radius of the earth (miles) at 39 degrees from the equator
Rk : 6373, // mean radius of the earth (km) at 39 degrees from the equator
// convert degrees to radians
deg2rad : function (deg) {
var rad = deg * Math.PI / 180; // radians = degrees * pi/180
return rad;
},
// round to the nearest 1/1000
round : function (x) {
return Math.round(x * 1000) / 1000;
},
/* main function */
findDistance : function (lat1, lon1, lat2, lon2) {
var t1, n1, t2, n2, dlat, dlon, a, c, dm, dk, mi, km;
// get values for lat1, lon1, lat2, and lon2
t1 = lat1;
n1 = lon1;
t2 = lat2;
n2 = lon2;
// convert coordinates to radians
lat1 = Haversine.deg2rad(t1);
lon1 = Haversine.deg2rad(n1);
lat2 = Haversine.deg2rad(t2);
lon2 = Haversine.deg2rad(n2);
// find the differences between the coordinates
dlat = lat2 - lat1;
dlon = lon2 - lon1;
// here's the heavy lifting
a = Math.pow(Math.sin(dlat/2), 2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(dlon/2), 2);
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); // great circle distance in radians
dm = c * Haversine.Rm; // great circle distance in miles
dk = c * Haversine.Rk; // great circle distance in km
// round the results down to the nearest 1/1000
mi = Haversine.round(dm);
km = Haversine.round(dk);
// display the result
console.log(mi + 'miles');
console.log(km + 'km');
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment