Calculate Distance

5 parameters

5 of 6

function calculateDistance(lat1, lon1, lat2, lon2, unit)

Calculates the distance between two geographic coordinates using the Haversine formula

Parameters

Name
Type
Required
Description
lat1numberRequiredLatitude of the first point
lat2numberRequiredLatitude of the second point
lon1numberRequiredLongitude of the first point
lon2numberRequiredLongitude of the second point
unitstringOptionalUnit of measurement (km or miles)

Function Implementation

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);
  }
}