Last active
August 8, 2024 08:51
-
-
Save jferrao/cb44d09da234698a7feee68ca895f491 to your computer and use it in GitHub Desktop.
Kotlin implementation of the Haversine formula
This file contains 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
class Geo(private val lat: Double, private val lon: Double) { | |
companion object { | |
const val earthRadiusKm: Double = 6372.8 | |
} | |
/** | |
* Haversine formula. Giving great-circle distances between two points on a sphere from their longitudes and latitudes. | |
* It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the | |
* sides and angles of spherical "triangles". | |
* | |
* https://rosettacode.org/wiki/Haversine_formula#Java | |
* | |
* @return Distance in kilometers | |
*/ | |
fun haversine(destination: Geo): Double { | |
val dLat = Math.toRadians(destination.lat - this.lat); | |
val dLon = Math.toRadians(destination.lon - this.lon); | |
val originLat = Math.toRadians(this.lat); | |
val destinationLat = Math.toRadians(destination.lat); | |
val a = Math.pow(Math.sin(dLat / 2), 2.toDouble()) + Math.pow(Math.sin(dLon / 2), 2.toDouble()) * Math.cos(originLat) * Math.cos(destinationLat); | |
val c = 2 * Math.asin(Math.sqrt(a)); | |
return earthRadiusKm * c; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
test