2016-09-30 77 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