Created
January 27, 2019 01:46
-
-
Save steniowagner/2e76570adbe9cfbf93e90d8eb55ec037 to your computer and use it in GitHub Desktop.
Calculate the distance between two coordinates (lat-lng).
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
const parseDegreeToRadians = (degrees) => degrees * (Math.PI / 180); | |
const calculateDistanceBetweenTwoCoordinates = (firstCoordinate, secondCoordinate) => { | |
const EARTH_RADIUS = 6371; | |
const deltaLatitude = parseDegreeToRadians(secondCoordinate.latitude - firstCoordinate.latitude); | |
const deltaLongitude = parseDegreeToRadians(secondCoordinate.longitude - firstCoordinate.longitude); | |
const haversinesInnerTerm = Math.sin(deltaLatitude / 2) * Math.sin(deltaLatitude / 2) + | |
Math.cos(parseDegreeToRadians(firstCoordinate.latitude)) * Math.cos(parseDegreeToRadians(secondCoordinate.longitude)) * | |
Math.sin(deltaLongitude / 2) * Math.sin(deltaLongitude / 2); | |
const haversinesOutterTerm = 2 * Math.atan2(Math.sqrt(haversinesInnerTerm), Math.sqrt(1 - haversinesInnerTerm)); | |
const distance = EARTH_RADIUS * haversinesOutterTerm; | |
return distance; | |
}; | |
module.exports = calculateDistanceBetweenTwoCoordinates; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment