Skip to content

Instantly share code, notes, and snippets.

@betiol
Last active May 9, 2017 18:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save betiol/252aed96e1cea2e587f0f7f48b5e6a00 to your computer and use it in GitHub Desktop.
Save betiol/252aed96e1cea2e587f0f7f48b5e6a00 to your computer and use it in GitHub Desktop.
Get distance by Latitude & Longitude KM/Meters/Miles
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