How can I calculate the distance between two coordinates (latitude and longitude) in JavaScript?
Davide S
davide s profile pic

To calculate the distance between two coordinates specified by latitude and longitude in JavaScript, you can use the Haversine formula. The Haversine formula calculates the great-circle distance between two points on the surface of a sphere (in this case, the Earth) given their latitudes and longitudes. Here's an example implementation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

function calculateDistance(lat1, lon1, lat2, lon2) {
  const earthRadius = 6371; // Radius of the Earth in kilometers
  const dLat = toRadians(lat2 - lat1);
  const dLon = toRadians(lon2 - lon1);

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

  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  const distance = earthRadius * c;

  return distance;
}

function toRadians(degrees) {
  return degrees * (Math.PI / 180);
}

// Example usage
const distance = calculateDistance(37.7749, -122.4194, 34.0522, -118.2437);
console.log(distance.toFixed(2) + ' km'); // Output: 559.03 km

In this example, thecalculateDistance function takes four arguments:lat1 andlon1 representing the latitude and longitude of the first point, andlat2 andlon2 representing the latitude and longitude of the second point. The Haversine formula requires the input to be in radians, so thetoRadians function is used to convert the degrees to radians. The formula then computes the differences in latitude and longitude (dLat anddLon), applies the Haversine formula, and calculates the great-circle distance (distance) in kilometers. Please note that this calculation assumes a perfect spherical Earth, which is a simplification. In practice, the Earth is an oblate spheroid, so for very long distances or high precision, more complex models may be necessary. Additionally, be aware that this calculation does not account for factors like altitude, which may affect the actual distance between two points.