HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

How can I calculate the distance between two coordinates using JavaScript?

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
distancejavascripttwohowbetweencoordinatescalculatethecanusing

Problem

I've recently come across a problem where I needed to calculate the distance between two sets of latitude and longitude coordinates. This is a common task in many applications, such as mapping services, location-based services, and geocoding.
Luckily, the complicated math for it has already been done for us. We can simply use the Haversine formula to calculate the distance between two points on the Earth's surface given their latitude and longitude coordinates.
<latex-expression>
<figure>
</figure>

Solution

d = 2 \times r \times \arcsin\left(\sqrt{\sin^2\left(\frac{d\phi}{2}\right) + \cos(\phi_1) \cdot \cos(\phi_2) \cdot \sin^2\left(\frac{d\lambda}{2}\right)}\right)


<latex-expression>
<figure>
</figure>
Where:
  • d is the distance between the two points
  • r is the radius of the Earth

Code Snippets

d = 2 \times r \times \arcsin\left(\sqrt{\sin^2\left(\frac{d\phi}{2}\right) + \cos(\phi_1) \cdot \cos(\phi_2) \cdot \sin^2\left(\frac{d\lambda}{2}\right)}\right)
const coordinateDistance = (lat1, lon1, lat2, lon2) => {
  // Convert degrees to radians
  const radLat1 = lat1 * Math.PI / 180;
  const radLon1 = lon1 * Math.PI / 180;
  const radLat2 = lat2 * Math.PI / 180;
  const radLon2 = lon2 * Math.PI / 180;

  // Radius of the Earth in meters
  const R = 6_371_000; // m

  // Differences in coordinates
  const dLat = radLat2 - radLat1;
  const dLon = radLon2 - radLon1;

  // Haversine formula
  const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
            Math.cos(radLat1) * Math.cos(radLat2) *
            Math.sin(dLon / 2) * Math.sin(dLon / 2);

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

  return distance.toFixed(2); // Return distance rounded to 2 decimal places
};

// Sample usage:
const lat1 = 40.7128; // New York City
const lon1 = -74.0060;
const lat2 = 34.0522; // Los Angeles
const lon2 = -118.2437;

coordinateDistance(lat1, lon1, lat2, lon2); // 3935746.25 (meters)

Context

From 30-seconds-of-code: distance-of-two-lat-lng-coordinates

Revisions (0)

No revisions yet.