Last active
July 5, 2018 02:44
-
-
Save ezy/60042f83c3e1683aa9963dd5cb1aa2c8 to your computer and use it in GitHub Desktop.
Haversine formula - calculate distance in metres between two sets of co-ordinates
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
function CalculateDistance(lat1, lon1, lat2, lon2) { | |
function toRad(x) { | |
return x * Math.PI / 180; | |
} | |
let R = 6371000; // set formula in metres | |
// Magic | |
let x1 = lat2 - lat1; | |
let dLat = toRad(x1); | |
let x2 = lon2 - lon1; | |
let dLon = toRad(x2); | |
let a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + | |
Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * | |
Math.sin(dLon / 2) * Math.sin(dLon / 2); | |
let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); | |
let d = R * c; | |
// return value to 2 dp | |
return d.toFixed(2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment