Skip to content

Instantly share code, notes, and snippets.

@orispok
Created August 8, 2024 08:47
Show Gist options
  • Save orispok/b2d53ce4ac8d07c0ec39073931bce048 to your computer and use it in GitHub Desktop.
Save orispok/b2d53ce4ac8d07c0ec39073931bce048 to your computer and use it in GitHub Desktop.
haversine formula - Kotlin Multiplatform
import kotlin.math.asin
import kotlin.math.cos
import kotlin.math.sqrt
import kotlin.math.PI
fun toRadians(deg: Double): Double = deg / 180.0 * PI
data class Location(
val lat: Double,
val lon: Double,
) {
companion object {
const val EARTH_RADIUS_KM: Double = 6371.0
}
/**
* Calculates the Haversine distance between this location and the destination location.
* For more information, see [Haversine formula](https://en.wikipedia.org/wiki/Haversine_formula#:~:text=The%20haversine%20formula%20determines%20the,and%20angles%20of%20spherical%20triangles).
*/
fun haversine(destination: Location): Double {
val dGama = toRadians(destination.lat - this.lat)
val dLambda = toRadians(destination.lon - this.lon)
val originLat = toRadians(this.lat)
val destinationLat = toRadians(destination.lat)
val a = 1 - cos(dGama) + cos(originLat) * cos(destinationLat) * (1 - cos(dLambda))
return EARTH_RADIUS_KM * 2 * asin(sqrt(a/2))
}
}
fun main(){
val nebraska = Location(41.507483, -99.436554)
val distance = nebraska.haversine(nebraska)
println("distance to same location: $distance")
val kansas = Location(38.504048, -98.315949)
val result = nebraska.haversine(kansas)
println("distance on map 347.3 result: $result")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment