2016-09-30 40 views
4

我有以下火力地堡的数据库结构,过滤火力地堡数据库基于位置半径

"-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" 
} 

我需要过滤一定的距离参数范围内的职位(小于50M,100M,150米& 200米),我可以得到从“经度”&“纬度”坐标,但我努力过滤帖子。任何帮助将不胜感激。

非常感谢提前。新手加入Firebase & Swift。

+1

看看Geofire:https://github.com/firebase/geofire-objc –

回答

0

以下是您可以尝试的解决方案。假设您已将所有帖子从Firebase下载到应用并存储在阵列中。你也可以考虑使用我没有亲自使用过的GeoFire(但愿)。我相信它可以让您按位置查询Firebase,因此您不必首先将所有帖子下载到用户设备并在客户端进行过滤。

// assumes you have set up the app to get the user's 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's 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

接受这个答案,如果它解决了你的问题:)快乐编码 – Dravidian