Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent Math.toRadians() using kotlin.math

I would like to know if there is an equivalent Math.toRadians in kotlin.

I need to calculate distance between 2 locations on earth sphere.

Got this haversine formula from this gist

https://gist.github.com/jferrao/cb44d09da234698a7feee68ca895f491

internal class DistanceCalculator(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;
    }

}

I need to use it without any java lib in an sdk from a kmm project.

Thanks for any help.

like image 651
Pablo R. Avatar asked Sep 08 '26 06:09

Pablo R.


1 Answers

This should do the trick(reverse as well)

import kotlin.math.PI
        
fun toRadians(deg: Double): Double = deg / 180.0 * PI

fun toDegrees(rad: Double): Double = rad * 180.0 / PI
like image 55
PaulNUK Avatar answered Sep 13 '26 05:09

PaulNUK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!