Created
February 9, 2019 15:21
-
-
Save mikaelvesavuori/250ae74d18624108818cdc4d06c56c6b to your computer and use it in GitHub Desktop.
Calculate distance between two positions, given as object with LAT and LONG coordinates
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
// Entirely based on answer given in: https://stackoverflow.com/questions/27928/calculate-distance-between-two-latitude-longitude-points-haversine-formula | |
export default function calculateDistance(position1, position2) { | |
//lon1, lat1, lon2, lat2 | |
const R = 6371; // Radius of the earth in km | |
const dLat = (position2.latitude - position1.latitude).toRad(); | |
const dLon = (position2.longitude - position1.longitude).toRad(); | |
const a = | |
Math.sin(dLat / 2) * Math.sin(dLat / 2) + | |
Math.cos(position1.latitude.toRad()) * | |
Math.cos(position2.latitude.toRad()) * | |
Math.sin(dLon / 2) * | |
Math.sin(dLon / 2); | |
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); | |
const d = R * c; // Distance in km | |
return d; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment