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