Darren
Darren

Reputation: 74

Room database custom order by functionality

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>

Upvotes: 0

Views: 77

Answers (0)

Related Questions