// ------------------------------------------------------------
// Convert degrees to radians
// ------------------------------------------------------------
function degToRad(deg: number): number {
return deg * Math.PI / 180.0;
}
// ------------------------------------------------------------
// Compute the great-circle distance between two points on Earth
// using the Haversine formula.
// lat1, lon1, lat2, lon2 are in degrees.
// The result is returned in kilometers.
// ------------------------------------------------------------
function haversine(lat1: number, lon1: number,
lat2: number, lon2: number): number {
// Earth's mean radius in kilometers
const R: number = 6371.0;
// Convert all angles to radians
const rlat1: number = degToRad(lat1);
const rlon1: number = degToRad(lon1);
const rlat2: number = degToRad(lat2);
const rlon2: number = degToRad(lon2);
// Differences
const dlat: number = rlat2 - rlat1;
const dlon: number = rlon2 - rlon1;
// Haversine formula
// a is the Haversine of the central angle between the two points.
const a: number =
Math.sin(dlat / 2) ** 2 +
Math.cos(rlat1) * Math.cos(rlat2) *
Math.sin(dlon / 2) ** 2;
// Central angle
// c is the central angle between the two points on the Earth’s surface.
const c: number = 2 * Math.asin(Math.sqrt(a));
// Final distance
return R * c;
}
// ------------------------------------------------------------
// Main
// ------------------------------------------------------------
// Example coordinates:
// Austin, Texas
const lat1: number = 30.2672;
const lon1: number = -97.7431;
// Houston, Texas
const lat2: number = 29.7604;
const lon2: number = -95.3698;
// Calculate distances
const distanceKm: number = haversine(lat1, lon1, lat2, lon2);
// Convert kilometers to miles
const distanceMiles: number = distanceKm * 0.621371;
// Output results
console.log(`Distance: ${distanceKm.toFixed(3)} km`);
console.log(`Distance: ${distanceMiles.toFixed(3)} miles`);
/*
run:
Distance: 235.352 km
Distance: 146.241 miles
*/