26 lines
1.0 KiB
TypeScript
26 lines
1.0 KiB
TypeScript
const EARTH_RADIUS_KM = 6371;
|
|
|
|
// Initial great-circle bearing from point 1 to point 2 (v0.36.0), degrees true [0, 360).
|
|
export function initialBearingDeg(lat1: number, lon1: number, lat2: number, lon2: number): number {
|
|
const toRad = (d: number) => (d * Math.PI) / 180;
|
|
const phi1 = toRad(lat1);
|
|
const phi2 = toRad(lat2);
|
|
const dLon = toRad(lon2 - lon1);
|
|
const theta = Math.atan2(
|
|
Math.sin(dLon) * Math.cos(phi2),
|
|
Math.cos(phi1) * Math.sin(phi2) - Math.sin(phi1) * Math.cos(phi2) * Math.cos(dLon),
|
|
);
|
|
return (theta * 180 / Math.PI + 360) % 360;
|
|
}
|
|
|
|
// Great-circle distance between two WGS84 points (haversine), in km.
|
|
export function haversineKm(lat1: number, lon1: number, lat2: number, lon2: number): number {
|
|
const toRad = (d: number) => (d * Math.PI) / 180;
|
|
const dLat = toRad(lat2 - lat1);
|
|
const dLon = toRad(lon2 - lon1);
|
|
const a =
|
|
Math.sin(dLat / 2) ** 2 +
|
|
Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLon / 2) ** 2;
|
|
return 2 * EARTH_RADIUS_KM * Math.asin(Math.min(1, Math.sqrt(a)));
|
|
}
|