Last active
October 5, 2021 21:43
-
-
Save crftr/1cccc9cc82761ef1127af8225e460e0b to your computer and use it in GitHub Desktop.
Calculate the distance between two latitude/longitude coordinate pairs using the haversine formula.
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
/* By default this will return the distance in kilometers, but will return | |
* miles when the inMiles argument is true. | |
*/ | |
function haversineEarthDistance(lat1, lon1, lat2, lon2, inMiles) { | |
function toRads(x) { return (x * Math.PI) / 180; } | |
var EARTH_RADIUS_KM = 6373; | |
var KM_PER_MI = 1.609344; | |
var dLat = toRads(lat2 - lat1); | |
var dLon = toRads(lon2 - lon1); | |
var a = | |
Math.sin(dLat / 2) * Math.sin(dLat / 2) + | |
Math.cos(toRads(lat1)) * | |
Math.cos(toRads(lat2)) * | |
Math.sin(dLon / 2) * | |
Math.sin(dLon / 2); | |
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); | |
if (inMiles) { | |
return (EARTH_RADIUS_KM * c) / KM_PER_MI; | |
} else { | |
return EARTH_RADIUS_KM * c; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment