Last active
May 9, 2017 18:25
-
-
Save betiol/252aed96e1cea2e587f0f7f48b5e6a00 to your computer and use it in GitHub Desktop.
Get distance by Latitude & Longitude KM/Meters/Miles
This file contains 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
var Distance = (function () { | |
var toRad = function (num) { | |
return num * Math.PI / 180 | |
} | |
return function Distance(start, end, options) { | |
options = options || {} | |
var radii = { | |
km: 6371, | |
mile: 3960, | |
meter: 6371000, | |
nmi: 3440 | |
} | |
var R = options.unit in radii | |
? radii[options.unit] | |
: radii.km | |
var dLat = toRad(end.latitude - start.latitude) | |
var dLon = toRad(end.longitude - start.longitude) | |
var lat1 = toRad(start.latitude) | |
var lat2 = toRad(end.latitude) | |
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)) | |
if (options.threshold) { | |
return options.threshold > (R * c) | |
} | |
return R * c | |
} | |
})() | |
export { Distance } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment