1

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
rendom
  • 3,417
  • 6
  • 38
  • 49

1 Answers1

3

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

Francisco Durdin Garcia
  • 12,540
  • 9
  • 53
  • 95
  • 1
    what about this issue. All the documents we get are within the lat range, but not within the lon range https://stackoverflow.com/questions/46630507/how-to-run-a-geo-nearby-query-with-firestore?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa#comment85444540_46920982 – rendom May 21 '18 at 16:19