rendom
rendom

Reputation: 3705

Firebase: Query by nearest location

Firebase can store documents with Geopoint object. https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/GeoPoint

But we can't use range filter on different fields and this is necessary for location querying.

As I understand year ago there was functionality to make such queries using Geofire Query for nearby locations

But now it is obsolete and not working.

What is current solution?

Upvotes: 1

Views: 2455

Answers (1)

Francisco Durdin Garcia
Francisco Durdin Garcia

Reputation: 13347

You can query using GeoPoint Firestore objects and GreatherThan clause together with LessThan. You should add your own accuracy to instead of use just one mile of distance.

fun Query.getNearestLocation(latitude: Double, longitude: Double, distance: Double): Query {
    // ~1 mile of lat and lon in degrees
    val lat = 0.0144927536231884
    val lon = 0.0181818181818182

    val lowerLat = latitude - (lat * distance)
    val lowerLon = longitude - (lon * distance)

    val greaterLat = latitude + (lat * distance)
    val greaterLon = longitude + (lon * distance)

    val lesserGeopoint = GeoPoint(lowerLat, lowerLon)
    val greaterGeopoint = GeoPoint(greaterLat, greaterLon)

    val docRef = FirebaseFirestore.getInstance().collection("locations")
    return docRef
            .whereGreaterThan("location", lesserGeopoint)
            .whereLessThan("location", greaterGeopoint)
}

This code is a Kotlin translation from the code made by Ryan Lee on this post

Upvotes: 3

Related Questions