Created
January 10, 2018 12:04
-
-
Save jhsuZerion/15443d281f12f3f933281e745036c518 to your computer and use it in GitHub Desktop.
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
function haversineDistance(latitude1, longitude1, latitude2, longitude2, unit) { | |
if(typeof latitude1 === "undefined" || typeof longitude1 === "undefined" || typeof latitude2 === "undefined" || typeof longitude2 === "undefined") return -1; | |
unit = (typeof unit === "undefined") ? "km" : unit; | |
// convert to Number | |
latitude1 = Number(latitude1); | |
longitude1 = Number(longitude1); | |
latitude2 = Number(latitude2); | |
longitude2 = Number(longitude2); | |
var R = 6371; | |
// Radius of the earth in km | |
var dLat = deg2rad(latitude2 - latitude1); | |
// deg2rad below | |
var dLon = deg2rad(longitude2 - longitude1); | |
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(deg2rad(latitude1)) * Math.cos(deg2rad(latitude2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2); | |
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); | |
// Distance in km | |
var d = R * c; | |
switch (unit) { | |
case "km": | |
return d; | |
case "m": | |
return d * 1000; | |
case "nm": | |
return d / 1.852; | |
case "miles": | |
return d / 1.609344; | |
case "feet": | |
return d / 0.0003048; | |
} | |
} | |
function deg2rad(deg) { | |
return deg * (Math.PI / 180); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment