Created
August 8, 2024 08:47
-
-
Save orispok/b2d53ce4ac8d07c0ec39073931bce048 to your computer and use it in GitHub Desktop.
haversine formula - Kotlin Multiplatform
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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