function calculateDistance(lat1, lon1, lat2, lon2, unit)
Calculates the distance between two geographic coordinates using the Haversine formula
Name↑ | Type | Required | Description |
|---|---|---|---|
| lat1 | number | Required | Latitude of the first point |
| lat2 | number | Required | Latitude of the second point |
| lon1 | number | Required | Longitude of the first point |
| lon2 | number | Required | Longitude of the second point |
| unit | string | Optional | Unit of measurement (km or miles) |
function calculateDistance(lat1, lon1, lat2, lon2, unit = 'km') {
const R = unit === 'km' ? 6371 : 3959; // Earth's radius
const dLat = toRad(lat2 - lat1);
const dLon = toRad(lon2 - lon1);
const a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
function toRad(deg) {
return deg * (Math.PI/180);
}
}