Calculate the distance in kilometers between two coordinates with JavaScript

Calculate the distance in kilometers between two coordinates with JavaScript

In this article, we will see how to implement this calculation in JavaScript using the haversine formula, a widely used method for determining the distance between two points on a sphere.

Calculating the distance between two points on the Earth's surface, expressed in geographic coordinates (latitude and longitude), is a common problem in applications involving geolocation. In this article, we will see how to implement this calculation in JavaScript using the haversine formula, a widely used method for determining the distance between two points on a sphere.

The haversine formula is an equation that allows you to calculate the distance of the shortest path (the "orthodromic distance") between two points on a sphere, specifically on the Earth's surface, taking into account the curvature of the planet.

The formula is as follows:

a=sin2(Δφ2)+cos(φ1)cos(φ2)sin2(Δλ2)a = \sin^2\left(\frac{\Delta \varphi}{2}\right) + \cos(\varphi_1) \cdot \cos(\varphi_2) \cdot \sin^2\left(\frac{\Delta \lambda}{2}\right)

c=2atan2(a,1a)c = 2 \cdot \text{atan2}\left(\sqrt{a}, \sqrt{1-a}\right)

d=Rcd = R \cdot c

Since the haversine formula uses values ​​in radians, we must first convert the coordinates (expressed in degrees) to radians.


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

Here is the main function that implements the haversine formula.


function haversineDistance(lat1, lon1, lat2, lon2) {
  // Mean radius of the Earth in kilometers
  const R = 6371;

  // Convert latitudes and longitudes from degrees to radians
  const phi1 = toRadians(lat1);
  const phi2 = toRadians(lat2);
  const deltaPhi = toRadians(lat2 - lat1);
  const deltaLambda = toRadians(lon2 - lon1);

  // Apply the haversine formula
  const a = Math.sin(deltaPhi / 2) * Math.sin(deltaPhi / 2) +
            Math.cos(phi1) * Math.cos(phi2) *
            Math.sin(deltaLambda / 2) * Math.sin(deltaLambda / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

  // Distance in kilometers
  const distance = R * c;

  return distance;
}

Suppose we want to calculate the distance between two cities, for example Rome (41.9028° N, 12.4964° E) and Milan (45.4642° N, 9.1900° E). We can call the haversineDistance function by passing the respective coordinates.


const romeLat = 41.9028;
const romeLon = 12.4964;
const milanLat = 45.4642;
const milanLon = 9.1900;

const distance = haversineDistance(romeLat, romeLon, milanLat, milanLon);
console.log(`The distance between Rome and Milan is ${distance.toFixed(2)} km.`);

By running the above code, we will get an approximate result:


The distance between Rome and Milan is 477.23 km.

Code explanation:

  1. Converting to radians: Since most JavaScript trigonometric functions such as Math.sin() and Math.cos() accept radians, we convert the degrees of the coordinates to radians.

  2. Calculating the haversine formula: We apply the steps of the haversine formula to determine the value of a and c.

  3. Calculating the distance: We multiply the radius of the Earth (R) by the central angle c, giving us the distance between the two points in kilometers.

Considerations

  • The radius of the Earth varies slightly between the equator and the poles. However, the approximation of 6371 km is generally accurate enough for most applications.
  • If you want to improve accuracy in some specific contexts, you can use the polar radius (6356.8 km) or the equatorial radius (6378.1 km).

Conclusion

Using JavaScript to calculate the distance between two geographic coordinates is quite simple thanks to the haversine formula. This technique is useful in many modern applications, such as navigation, geolocation, and location-based services. The code we have seen can easily be adapted or extended to include functionality such as calculating the distance in miles or using different approximations of the Earth's radius depending on the location.