0

In a room database if the table has a latitude and longitude column.

How can the return values of a Query be ordered using the ORDER BY statement in the query to show the same order as if I ordered using the function below?

private fun calculateDistance(
    sourceLatitude: Double,
    sourceLongitude: Double,
    destinationLatitude: Double,
    destinationLongitude: Double
): Double {
    val pk = (180f / Math.PI).toFloat()
    val a1 = sourceLatitude / pk
    val a2 = sourceLongitude / pk
    val b1 = destinationLatitude / pk
    val b2 = destinationLongitude / pk
    val t1 = cos(a1) * cos(a2) * cos(b1) * cos(b2)
    val t2 = cos(a1) * sin(a2) * cos(b1) * sin(b2)
    val t3 = sin(a1) * sin(b1)
    val tt = acos(t1 + t2 + t3)
    return 6366000 * tt
}

For example, how could the following ORDER by statement be achieved?

    @Query("SELECT * FROM example_table ORDER BY **Ordering based On ExampleItems latitude and longitude compared to the parameters latitude longitude**")
    fun getItems(latitude: Double, longitude: Double): List<ExampleItems>

Darren
  • 74
  • 1
  • 10
  • https://stackoverflow.com/questions/12672740/ordering-with-sqlite-by-nearest-latitude-longitude-coordinates – Tenfour04 Mar 24 '23 at 19:06
  • Shamefully the above link provides solutions for simplified order by's and is not as precise in terms of location accuracy as the function mentioned above. – Darren Mar 24 '23 at 19:26
  • I was just trying to help—no need to call it shameful. I don’t know how complicated you can get with math in a database statement. – Tenfour04 Mar 24 '23 at 22:05

0 Answers0