Last active
November 7, 2020 01:16
-
-
Save SimonJThompson/c9d01f0feeb95b18c7b0 to your computer and use it in GitHub Desktop.
Use haversine to calculate the distance in miles between two lat-long 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
/* Modified from http://stackoverflow.com/questions/14560999/using-the-haversine-formula-in-javascript */ | |
function toRad(v){return v * Math.PI / 180;} | |
function kmToMiles(km) {return (km * 0.62137).toFixed(2);} | |
var l1 = LatLong(0,0); | |
var l2 = LatLong(0,0); | |
function LatLong(lat, lon) { | |
return {Latitude: lat, Longitude: lon} | |
} | |
function haversine(l1, l2) { | |
var R = 6371; // km | |
var x1 = l2.Latitude-l1.Latitude; | |
var dLat = toRad(x1); | |
var x2 = l2.Longitude-l1.Longitude; | |
var dLon = toRad(x2); | |
var a = Math.sin(dLat/2) * Math.sin(dLat/2) + | |
Math.cos(toRad(l1.Latitude)) * Math.cos(toRad(l2.Latitude)) * | |
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; | |
} | |
alert(kmToMiles(haversine(l1, l2))+' miles'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment