Skip to content

Instantly share code, notes, and snippets.

@avspeed
Last active August 29, 2015 14:03
Show Gist options
  • Save avspeed/ab60168afe7362cc6e4b to your computer and use it in GitHub Desktop.
Save avspeed/ab60168afe7362cc6e4b to your computer and use it in GitHub Desktop.
JavaScript calculate distance between 2 points
function toRad(value) {
var RADIANT_CONSTANT = 0.0174532925199433;
return (value * RADIANT_CONSTANT);
}
function calculateDistance(starting, ending) {
var KM_RATIO = 6371;
try {
var dLat = toRad(ending.latitude - starting.latitude);
var dLon = toRad(ending.longitude - starting.longitude);
var lat1Rad = toRad(starting.latitude);
var lat2Rad = toRad(ending.latitude);
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1Rad) * Math.cos(lat2Rad);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = KM_RATIO * c;
return d;
} catch(e) {
return -1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment