@erexstudio/geo-span-measure
Version:
A simple npm package for calculating distance between two coordinates using the Haversine formula.
68 lines (55 loc) • 1.61 kB
JavaScript
// index.js
const haversineDistance = (coord1, coord2, unit = "kilometers") => {
if (!coord1 || !coord2) {
return { error: "Both coordinates are required." };
}
if (
!Array.isArray(coord1) ||
coord1.length !== 2 ||
!Array.isArray(coord2) ||
coord2.length !== 2
) {
return {
error:
"Invalid coordinates. Please provide arrays with latitude and longitude values for both coordinates.",
};
}
const [lat1, lon1] = coord1;
const [lat2, lon2] = coord2;
if (
typeof lat1 !== "number" ||
typeof lon1 !== "number" ||
typeof lat2 !== "number" ||
typeof lon2 !== "number"
) {
return {
error:
"Invalid coordinate values. Latitude and longitude should be numbers.",
};
}
const earthRadius = {
kilometers: 6357,
miles: 3950,
meters: 6371000,
};
if (!earthRadius[unit]) {
return {
error: `Invalid unit. Supported units are 'kilometers', 'miles', and 'meters'.`,
};
}
const R = earthRadius[unit];
const dLat = degToRad(lat2 - lat1);
const dLon = degToRad(lon2 - lon1);
const a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(degToRad(lat1)) *
Math.cos(degToRad(lat2)) *
Math.sin(dLon / 2) *
Math.sin(dLon / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
const distance = R * c;
const formattedDistance = parseFloat(distance.toFixed(2));
return formattedDistance;
};
const degToRad = (deg) => deg * (Math.PI / 180);
module.exports = haversineDistance;