Location Radius Firebase Filter Database

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 messages within certain distance parameters (less than 50 m, 100 m, 150 m and 200 m). I can get the coordinate from "longitude" and "latitude", but I'm struggling to filter the messages. Any help would be greatly appreciated.

Thank you very much in advance. New to Firebase and Swift.

+4
source share
2 answers

. , , Firebase . GeoFire, ( ). , Firebase , .

// assumes you have set up the app to get the user current location
var currentLocation: CLLocation?

// Your array of posts downloaded from Firebase
var postArray = [post]()

let metersInTwentyFiveMiles = 40233.6

// You could put this in viewDidAppear after you load the post array from Firebase
for post in postArray {

    var distanceInMeters: CLLocationDistance = 0

    let postLocation = CLLocation(latitude: post.latitude, longitude: post.longitude)


    if let currentLocation = self.currentLocation {
         // Set distanceInMeters to the distance between the user current location and the location of the post.
         distanceInMeters = currentLocation.distanceFromLocation(postLocation)
         // If this distance is not within 25 miles, remove this post from the array
         if self.metersInTwentyFiveMiles < distanceInMeters {
            self.posts = self.posts.filter{ $0 != post }
       }
    }
}
0

JSON : -

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

: -

    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)

            }
        }
    })
}

autoID 30 60. , , , , .

0

Source: https://habr.com/ru/post/1656360/


All Articles