1

I have an iOS Swift project running with PHP back-end. The app gets user location (lng & lat), posts to API (back-end), and receives data back. The data is a list of locations nearby user's location.

Now, I move to Firebase. The data structure is like:

Firebase data structure

And the code I tried to get data from Firebase:

let radius: Double = 0.7
    
let lng_min = lng - radius/abs(cos(deg2rad(lat))*69)
let lng_max = lng + radius/abs(cos(deg2rad(lat))*69)

let lat_min = lat - (radius/69)
let lat_max = lat + (radius/69)

ref = FIRDatabase.database().reference()
ref.child("v1")
    .queryOrderedByChild("lng")
    .queryStartingAtValue(lng_min)
    .queryEndingAtValue(lng_max)
    .queryOrderedByChild("lat")
    .queryStartingAtValue(lat_min)
    .queryEndingAtValue(lat_max)
    .observeEventType(.Value, withBlock: { snapshot in
        print(snapshot.childrenCount)
    })

App crashed while run with error: Cannot use multiple queryOrderedBy calls!

How can I query on Firebase like SQL query below?

SELECT lat, lng FROM `table`
WHERE (lng BETWEEN lng_min AND lng_max) //~> lng_min <= lng <= lng_max
AND (lat BETWEEN lat_min AND lat_max)
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Shinichi
  • 475
  • 4
  • 7
  • 25
  • 1
    Firebase can indeed only use one orderBy clause in a query. For a general answer on how you can sometimes query on multiple values, see [this question](http://stackoverflow.com/questions/26700924/query-based-on-multiple-where-clauses-in-firebase). But for querying longitude and latitude, there is a dedicated library called [GeoFire](https://github.com/firebase/geofire). – Frank van Puffelen May 30 '16 at 14:52
  • If you need to use GeoFire make sure you are not using the new Firebase v3, because this library has not been currently migrated to work fully with new version – Ymmanuel Jun 01 '16 at 23:00

0 Answers0