Pardeep Sharma
04/16/2023, 9:56 PM@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
searchResults.sortedBy { (x, y) -> x.location.distance() - y.location.distance() }
Is it possible since I am not able to achieve it..Paulo Meurer
04/17/2023, 6:20 AMval currentLat = ...
val currentLong = ...
val sortedSearchResults = searchResults.sortedBy {
it.geometry.location.distance(currentLat, currentLong)
}
Pardeep Sharma
04/17/2023, 6:22 AMPaulo Meurer
04/17/2023, 7:12 AM