Last active
May 31, 2024 08:49
-
-
Save simonwhatley/a0cb4aa23696dd502d6bf54b26edc30a to your computer and use it in GitHub Desktop.
Get the distance between two locations (latitude and longitude)
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
getDistance = (origin, destination, unit = 'mi') => { | |
// Convert degrees to radians | |
const earthRadius = { | |
'km': 6371, // Earth radius in kilometers | |
'mi': 3959 // Earth radius in miles | |
}; | |
const originRad = origin.latitude * Math.PI / 180 | |
const destinationRad = destination.latitude * Math.PI / 180 | |
const dLat = destinationRad - originRad | |
const dLon = (destination.longitude - origin.longitude) * Math.PI / 180 | |
const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + | |
Math.cos(originRad) * Math.cos(destinationRad) * | |
Math.sin(dLon / 2) * Math.sin(dLon / 2) | |
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)) | |
const distance = earthRadius[unit] * c | |
return distance | |
} | |
// Birmingham New Street station | |
const origin = { | |
latitude: 52.478150, | |
longitude: -1.898960 | |
} | |
// London Euston station | |
const destination = { | |
latitude: 51.526450, | |
longitude: -0.133740 | |
} | |
// distance: 99.8090447964715 miles | |
console.log(getDistance(origin, destination)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment