Last active
January 30, 2016 15:22
-
-
Save kevboutin/a498be3f22ab4eebda8e to your computer and use it in GitHub Desktop.
Calculate shortest distance between two points
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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