Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,406 questions

56,397 answers

573 users

How to calculate the distance between two latitude-longitude points in Scala

1 Answer

0 votes
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

*/

 



answered Aug 7 by avibootz
edited Aug 7 by avibootz

Related questions

...