Skip to content

Instantly share code, notes, and snippets.

@vitorfranca
Created August 30, 2018 18:48
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 vitorfranca/a2ed1629d4278456a0d2583ac9ba44f9 to your computer and use it in GitHub Desktop.
Save vitorfranca/a2ed1629d4278456a0d2583ac9ba44f9 to your computer and use it in GitHub Desktop.
Calculates the distance in Km between two earth coordinates
function degreesToRadians(degrees) {
return degrees * Math.PI / 180;
}
function distanceInKmBetweenEarthCoordinates(lat1, lon1, lat2, lon2) {
var earthRadiusKm = 6371;
var dLat = degreesToRadians(lat2-lat1);
var dLon = degreesToRadians(lon2-lon1);
lat1 = degreesToRadians(lat1);
lat2 = degreesToRadians(lat2);
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return earthRadiusKm * c;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment