Skip to content

Instantly share code, notes, and snippets.

@raco
Last active May 15, 2020 19:20
Show Gist options
  • Save raco/f0f015375d44f88ac2e55a46c13bc6a2 to your computer and use it in GitHub Desktop.
Save raco/f0f015375d44f88ac2e55a46c13bc6a2 to your computer and use it in GitHub Desktop.
Calculate distance in km between 2 positions
export function getDistanceFromLocationsInKm(
latStart: number,
longStart: number,
latEnd: number,
longEnd: number
): number {
const R = 6371; // Radius of the earth in km
const dLat = _deg2rad(latEnd - latStart);
const dLong = _deg2rad(longEnd - longStart);
const a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(_deg2rad(latStart)) * Math.cos(_deg2rad(latEnd)) * Math.sin(dLong / 2) * Math.sin(dLong / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
const d = R * c; // Distance in km
return +d.toFixed(2);
}
function _deg2rad(deg) {
return deg * (Math.PI / 180);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment