DEV Community

Ayushman Chaturvedi
Ayushman Chaturvedi

Posted on

Measure Distance Between Two Locations in JavaScript Using the Haversine Formula

Have you ever been curious to explore about how far two places are from each other just by using their latitude and longitude? Maybe you're working on a map app, building a travel planner, or simply wondering how far apart your favorite cities are.

The most reliable way to calculate the distance between two points on the globe using Javascript is by using the Haversine equation. As long as you have the latitude and longitude for your starting point and destination, you can easily compute the distance between them.

Here’s how to calculate the distance in kilometers between two locations using JavaScript.

Step 1

When you get location data (gotten using the Geolocation API), the coordinates come in degrees. But the Haversine formula expects radians. So first, we'll write a little helper function to convert degrees to radians.

function degToRad(deg) {
  var rad = (deg * Math.PI)/180;
  return rad;
}
Enter fullscreen mode Exit fullscreen mode

Step 2

Now, let’s create the main function that actually calculates the distance between two points.

We’ll use the Haversine formula, which takes into account the spherical shape of the Earth (because the Earth isn’t flat... sorry if that's news 😄).

// Calculate distance between two coordinates
function calculateDistance(startCoords, destCoords) {
  const startingLat = degToRad(startCoords.latitude);
  const startingLong = degToRad(startCoords.longitude);
  const destinationLat = degToRad(destCoords.latitude);
  const destinationLong = degToRad(destCoords.longitude);

  // Radius of the Earth (in kilometers)
  const radius = 6371;

  // Haversine formula
  const distance = Math.acos(
    Math.sin(startingLat) * Math.sin(destinationLat) +
    Math.cos(startingLat) * Math.cos(destinationLat) *
    Math.cos(startingLong - destinationLong)
  ) * radius;

  return distance;
}
Enter fullscreen mode Exit fullscreen mode

Step 3

Now that we have our calculateDistance function, let's try it out with some sample coordinates.

const start = {
  latitude: 58.39343,
  longitude: -259.2627
};

const destination = {
  latitude: 43.8394,
  longitude: -129.3984
};

const distance = calculateDistance(start, destination);

console.log(`The distance between both locations is ${distance.toFixed(2)} km.`);
Enter fullscreen mode Exit fullscreen mode

Top comments (5)

Collapse
 
tarun_c5d7738bd5211c46683 profile image
Tarun

where is this used though

Collapse
 
ayushman profile image
Ayushman Chaturvedi

checkout my github repo github.com/ayushman247 , i have created a project based on this.

Collapse
 
nevodavid profile image
Nevo David

Been meaning to try thiswriting it like this just makes it legit simple. Copy-pasting immediately.

Collapse
 
kaibalya_jena_90a19acff39 profile image
kaibalya jena

Greattt

Collapse
 
lovish_verma_4514dcf70862 profile image
Lovish Verma

Impressive 🔥🔥🔥