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

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

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,623 questions

55,358 answers

573 users

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

1 Answer

0 votes
import kotlin.math.*

// ------------------------------------------------------------
// Convert degrees to radians
// ------------------------------------------------------------
fun degToRad(deg: Double): Double {
    return deg * 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.
// ------------------------------------------------------------
fun 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: Double = degToRad(lat1)
    val rlon1: Double = degToRad(lon1)
    val rlat2: Double = degToRad(lat2)
    val rlon2: Double = degToRad(lon2)

    // Differences
    val dlat: Double = rlat2 - rlat1
    val dlon: Double = rlon2 - rlon1

    // Haversine formula
    // a is the Haversine of the central angle between the two points.
    val a: Double =
        sin(dlat / 2).pow(2) +
        cos(rlat1) * cos(rlat2) *
        sin(dlon / 2).pow(2)

    // Central angle
    // c is the central angle between the two points on the Earth’s surface.
    val c: Double = 2 * asin(sqrt(a))

    // Final distance
    return R * c
}

fun main() {

    // 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("Distance: %.3f km".format(distanceKm))
    println("Distance: %.3f miles".format(distanceMiles))
}


/*
run:

Distance: 235.352 km
Distance: 146.241 miles

*/

 



answered 1 day ago by avibootz

Related questions

...