Skip to content

Instantly share code, notes, and snippets.

@kevboutin
Last active January 30, 2016 15:22
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 kevboutin/a498be3f22ab4eebda8e to your computer and use it in GitHub Desktop.
Save kevboutin/a498be3f22ab4eebda8e to your computer and use it in GitHub Desktop.
Calculate shortest distance between two points
function calculateDistance(lat1, lon1, lat2, lon2) {
var R = 6371; // km
var dLat = (lat2 - lat1).toRad();
var dLon = (lon2 - lon1).toRad();
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
return d;
}
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment