Skip to content

Instantly share code, notes, and snippets.

@13x54n
Created December 25, 2023 04:14
Show Gist options
  • Save 13x54n/ddd169c12165ca57c9535cacfe4516b9 to your computer and use it in GitHub Desktop.
Save 13x54n/ddd169c12165ca57c9535cacfe4516b9 to your computer and use it in GitHub Desktop.
function toRadians(degrees) {
return degrees * (Math.PI / 180);
}
function haversine(lat1, lon1, lat2, lon2) {
// @dev Earth radius in KM, if you want the final distance in miles change into 3958.8
const R = 6371;
const dLat = toRadians(lat2 - lat1);
const dLon = toRadians(lon2 - lon1);
// @dev a = sin²(φB - φA/2) + cos φA * cos φB * sin²(λB - λA/2)
const a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(toRadians(lat1)) * Math.cos(toRadians(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
// @dev c = 2 * atan2( √a, √(1−a) )
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
// @dev d = R ⋅ c
const distance = R * c;
return distance;
}
// @dev example usage
const distance = haversine(52.5200, 13.4050, 48.8566, 2.3522);
console.log(distance);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment