# Find Distance Between Two Locations in Kotlin

Most of the applications use Google Maps due to indicate places on Google Maps. We can use it to find the distance between two locations having coordinates latitude and longitude for those locations. But that gives by road distance. But in some scenarios, we only have to find a straight line distance between 2 latitudes and longitudes. In this article, we will discuss how you can calculate a straight line distance between two locations in Kotlin.

## Find Distance using Kotlin

In Kotlin we don’t have any built-in framework to calculate distance directly. But we can do it by using mathematical formulas in the following way.

``````fun distanceInKm(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {
val theta = lon1 - lon2
dist = Math.acos(dist)
dist = dist * 60 * 1.1515
dist = dist * 1.609344
return dist
}

private fun deg2rad(deg: Double): Double {
return deg * Math.PI / 180.0
}

return rad * 180.0 / Math.PI
}``````

This function takes 4 parameters which represent two coordinates, latitude, and longitude for both locations respectively. Makes mathematical calculations considering the circular earth. This function can be used in Android as well. Here you can find the last known location.

## Limitations of the above method

You might have got the idea till now that the above method returns the perpendicular distance not the by road distance. Although this perpendicular and straight line distance is enough for most of the cases. But if you are looking for By road distance then you need to use Google Direction API.

That’s It. This is how to Find Distance between two locations in Kotlin.

## Next

### Pull to Refresh Functionality in Kotlin Android ##### Shayan Naveed
Posts created 41

This site uses Akismet to reduce spam. Learn how your comment data is processed.

## Pick Multiple Images From Gallery in Kotlin – Android

Begin typing your search term above and press enter to search. Press ESC to cancel.