Skip to content

Instantly share code, notes, and snippets.

@zephster
Created April 28, 2014 17:48
Show Gist options
  • Save zephster/11379095 to your computer and use it in GitHub Desktop.
Save zephster/11379095 to your computer and use it in GitHub Desktop.
js haversine
function calculateNearestCity(myGeo, cityGeo)
{
//using the Haversine formula - http://en.wikipedia.org/wiki/Haversine_formula
var deg2rad = Math.PI / 180,
cos = Math.cos,
sin = Math.sin,
earth = 6371; //radius of earth in km
var derivedLat = (cityGeo.lat - myGeo.lat) * deg2rad,
derivedLon = (cityGeo.lon - myGeo.lon) * deg2rad;
var haversine = sin(derivedLat / 2) * sin(derivedLat / 2) +
cos(myGeo.lat * deg2rad) * cos(cityGeo.lat * deg2rad) *
sin(derivedLon / 2) * sin(derivedLon / 2);
return earth * (2 * Math.atan2(Math.sqrt(haversine), Math.sqrt(1-haversine)));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment