This module provides a robust, production-ready Haversine distance function for calculating the shortest (great-circle) distance between two latitude/longitude points on the Earth’s surface.
Uses the Haversine formula to calculate distance:
- Accounts for Earth's curvature
- More accurate than simple Pythagorean for global coordinates
Add the file to your project as src/index.js or use in your own module structure.
const calculateHaversine = require('./src/index')
const firstLocation = { lat: -6.2, lon: 106.8167 }
const secondLocation = { lat: -7.25, lon: 112.75 }
const distanceKm = calculateHaversine(firstLocation, secondLocation, 'km')
console.log('Distance (km):', distanceKm)
const distanceM = calculateHaversine(firstLocation, secondLocation, 'm')
console.log('Distance (m):', distanceM)calculateHaversine(firstLocation, secondLocation, distanceUnit)
- firstLocation
{ lat: number, lon: number } - secondLocation
{ lat: number, lon: number } - distanceUnit:
"km"or"m"
Returns:
- Number (distance between points, in requested unit)
Throws error if:
- Parameters are missing or invalid
- Distance unit is not "km" or "m"
Unit tests with Jest:
npm testTest file: test/haversine.test.js
MIT License © 2025 NeaByteLab