I do have following class structure that represent...
# android
p
I do have following class structure that represents Lat/Long of a Location with List<SearchResults>:
Copy code
@Serializable
data class SearchResults(
    val geometry: Geometry
) {
    @Serializable
    data class Geometry(
        val location: Location
    ) {
        @Serializable
        data class Location (
            @SerializedName("lat")
            val latitude: Double,
            @SerializedName("lng")
            val longitude: Double
            )

        fun Location.distance(fromLat: Double, fromLon: Double): Double {
            val radius = 6378137.0 // approximate Earth radius, *in meters*
            val deltaLat = fromLat - this.latitude
            val deltaLon = fromLon - this.longitude
            val angle = 2 * asin(
                sqrt(
                    sin(deltaLat / 2).pow(2.0) +
                            cos(fromLat) * cos(fromLat) *
                            sin(deltaLon / 2).pow(2.0)
                )
            )
            return radius * angle
        }
    }
}
I want to sort the places by distance as:
val searchResults: List<SearchResults> = listof(searchResultsFromRemote
Copy code
searchResults.sortedBy { (x, y) -> x.location.distance() - y.location.distance() }
Is it possible since I am not able to achieve it..
😁 1
not kotlin but kotlin colored 1
p
Hi! Do you want to sort distances from current user location? Then you could try something like:
Copy code
val currentLat = ...
val currentLong = ...
val sortedSearchResults = searchResults.sortedBy {
   it.geometry.location.distance(currentLat, currentLong)
}
p
No, I want to sort the list of locations with its lat/Long distances.
p
Then, maybe I don't get your question. Lat and Long are just a point. They don't represent a distance itself. Do you want to sort the distance from where? You will need a starting point.
147 Views