object HaversineDistance {
// ------------------------------------------------------------
// Convert degrees to radians
// ------------------------------------------------------------
def degToRad(deg: Double): Double =
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.
// ------------------------------------------------------------
def haversine(lat1: Double, lon1: Double,
lat2: Double, lon2: Double): Double = {
// Earth's mean radius in kilometers
val R: Double = 6371.0
// Convert all angles to radians
val rlat1 = degToRad(lat1)
val rlon1 = degToRad(lon1)
val rlat2 = degToRad(lat2)
val rlon2 = degToRad(lon2)
// Differences
val dlat = rlat2 - rlat1
val dlon = rlon2 - rlon1
// Haversine formula
// a is the Haversine of the central angle between the two points.
val a =
math.sin(dlat / 2) * math.sin(dlat / 2) +
math.cos(rlat1) * math.cos(rlat2) *
math.sin(dlon / 2) * math.sin(dlon / 2)
// Central angle
// c is the central angle between the two points on the Earth’s surface.
val c = 2 * math.asin(math.sqrt(a))
// Final distance
R * c
}
def main(args: Array[String]): Unit = {
// Example coordinates:
// Austin, Texas
val lat1: Double = 30.2672
val lon1: Double = -97.7431
// Houston, Texas
val lat2: Double = 29.7604
val lon2: Double = -95.3698
val distanceKm: Double = haversine(lat1, lon1, lat2, lon2)
// Convert kilometers to miles
val distanceMiles: Double = distanceKm * 0.621371
println(f"Distance: $distanceKm%.3f km")
println(f"Distance: $distanceMiles%.3f miles")
}
}
/*
run:
Distance: 235.352 km
Distance: 146.241 miles
*/