Files
2026-03-10 03:45:00 +09:00

20 lines
690 B
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
module.exports = (lon1, lat1, lon2, lat2) => {
// mean radius of earth's = 6,371km
const R = 6371;
// distance between latitude and longitude in radians
const dLat = ((lat2 - lat1) * Math.PI) / 180;
const dLon = ((lon2 - lon1) * Math.PI) / 180;
// haversine formula to calculate distance
const a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos((lat1 * Math.PI) / 180) *
Math.cos((lat2 * Math.PI) / 180) *
Math.sin(dLon / 2) *
Math.sin(dLon / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
const d = R * c;
// if (d > 1) return Math.round(d) + "km";
// else if (d <= 1) return Math.round(d * 1000) + "m";
return d;
};