
Haversine Algorithm: Calculate Distance Between Two Coordinates
Editor | March 1, 2026 | 5 min read
The Haversine algorithm is used to calculate the shortest distance over the Earth�s surface between two geographic coordinates (latitude and longitude). This is called the great-circle distance.
It is commonly used in delivery apps, ride-hailing, geofencing, and location-based search.
Inputs You Need
- latitude and longitude of point A
- latitude and longitude of point B
Coordinates are usually provided in degrees, but the formula requires radians.
Haversine Formula
[ 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 = 2 \cdot \operatorname{atan2}(\sqrt{a}, \sqrt{1-a}) ]
[ d = R \cdot c ]
Where:
- (\varphi) = latitude in radians
- (\lambda) = longitude in radians
- (\Delta\varphi) = difference in latitude
- (\Delta\lambda) = difference in longitude
- (R) = Earth radius (about 6371 km)
- (d) = distance
JavaScript Implementation
const toRadians = (degrees) => (degrees * Math.PI) / 180
export function haversineDistanceKm(lat1, lon1, lat2, lon2) {
const R = 6371 // Earth radius in kilometers
const phi1 = toRadians(lat1)
const phi2 = toRadians(lat2)
const deltaPhi = toRadians(lat2 - lat1)
const deltaLambda = toRadians(lon2 - lon1)
const a =
Math.sin(deltaPhi / 2) ** 2 +
Math.cos(phi1) * Math.cos(phi2) * Math.sin(deltaLambda / 2) ** 2
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
return R * c
}
If you want miles, multiply kilometers by 0.621371.
Example
const delhi = { lat: 28.6139, lon: 77.209 }
const mumbai = { lat: 19.076, lon: 72.8777 }
const km = haversineDistanceKm(delhi.lat, delhi.lon, mumbai.lat, mumbai.lon)
console.log(km.toFixed(2)) // ~1153.24 km
Practical Notes
- Haversine is accurate for most app-level use cases.
- For extremely high precision (survey-grade), use more advanced geodesic models.
- Always validate input ranges: latitude
-90..90, longitude-180..180.
Final Take
Use Haversine when you need a reliable and fast way to measure distance between two points on Earth. It is simple, well-known, and easy to implement in any backend or frontend stack.