Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter Firebase Database based on location radius

I have the following Firebase Database structure,

"-KSupX7CppMD1zbqIy0y" : {
  "addedByUser" : "zQpb7o18VzYsSoTQtT9DNhOqTUn2",
  "content" : "Post 1",
  "cost" : "20",
  "duration" : "Weekly",
  "latitude" : "40.7594479995956",
  "longitude" : "-73.9838934062393",
  "timestamp" : "Fri 30 Sep"
},
"-KSuphuqO6a0lnrJYUkt" : {
  "addedByUser" : "zQpb7o18VzYsSoTQtT9DNhOqTUn2",
  "content" : "Post 2",
  "cost" : "10",
  "duration" : "Daily",
  "latitude" : "40.7594329996462",
  "longitude" : "-73.9846261181847",
  "timestamp" : "Fri 30 Sep"
}

I need to filter the posts within certain distance parameters (less than 50m, 100m, 150m & 200m) I can get the coordinate from the "longitude" & "latitude" but I'm struggling to filter the posts. Any help would be greatly appreciated.

Many thanks in advance. Newbie to Firebase & Swift.

like image 528
David Lintin Avatar asked Sep 30 '16 12:09

David Lintin


1 Answers

For JSON like this:-

 UsersLocation :{
     autoID1 : {....},
     autoID2 : {.....}
           }

Try this:-

    FIRDatabase.database().reference().child("UsersLocation").queryOrdered(byChild: "lat").queryStarting(atValue: 30).queryEnding(atValue: 60).observeSingleEvent(of: .value, with: {(snap) in

        print(snap)


        if let snapDict = snap.value as? [String:AnyObject]{

            for each in snapDict{

                print(each)

            }
        }
    })
}

This will give you all the users with a autoID Key, with their latitude between 30 and 60, The order in which you retrieve data will be random, so to iterate through them in ascending order you can sort your dictionary that you receive .

like image 149
Dravidian Avatar answered Nov 20 '22 13:11

Dravidian