Android Calculate Distance Between 2 Gps Location (LatLng)

Jul 22, 2018
And a helper function to show distance as text
fun calculateDistance(lat1: Double, lng1: Double, lat2: Double, lng2: Double): Float {    val results = FloatArray(1)    Location.distanceBetween(lat1, lng1, lat2, lng2, results)    // distance in meter    return results[0]}

A helper function to show distance as text.

fun distanceText(distance: Float): String {    val distanceString: String    if (distance < 1000)        if (distance < 1)            distanceString = String.format(Locale.US, "%dm", 1)        else            distanceString = String.format(Locale.US, "%dm", Math.round(distance))    else if (distance > 10000)        if (distance < 1000000)            distanceString = String.format(Locale.US, "%dkm", Math.round(distance / 1000))        else            distanceString = "FAR"    else        distanceString = String.format(Locale.US, "%.2fkm", distance / 1000)    return distanceString}

Kotlin Extension

fun LatLng.toLocation() = Location("").apply {    latitude = latitude    longitude = longitude}fun LatLng.distanceTo(latLng: LatLng) = toLocation().distanceTo(latLng.toLocation())
val d = latLng1.distanceTo(latLng2)

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.