[swift] GeoFireを使用した位置情報書き込み、読み込み
目次
GeoFireを使用した位置情報書き込み、読み込み
特定の位置からある範囲の位置情報検索モジュール「GeoFire」を使った位置情報書き込み、読み込み
GeoFireのインストール方法は以下を参照
[swift] Firebase3.x.x + GeoFire2.x.x Install方法(位置範囲検索メソッド)
位置情報書き込み
*例ではlocationInfoという場所にデータを保存している
let latitude: CLLocationDegrees = 1.304843 //Singapore
let longitude: CLLocationDegrees = 103.831824 //Singapore
let key: String = "unique Key"
let geofireRef = FIRDatabase.database().reference().child("locationInfo")
let geoFire = GeoFire(firebaseRef: geofireRef)
geoFire.setLocation(CLLocation(latitude: latitude, longitude: longitude), forKey: key){ (error) in
if (error != nil) {
print("An error occurred: \(error)")
} else {
print("Saved location successfully!")
}
}
位置情報検索
*locationInfoから10km範囲で位置検索を実施
*検索が終了するとquery.observeReadyWithBlockが呼ばれる。
*検索で返ってくるデータは保存したKeyとCLLocation
let latitude: CLLocationDegrees = 1.304843 //Singapore
let longitude: CLLocationDegrees = 103.831824 //Singapore
let radius:Double = 10.0 //km
let geofireRef = FIRDatabase.database().reference().child("courseStart")
let geoFire = GeoFire(firebaseRef: locationInfo)
let center = CLLocation(latitude: latitude, longitude: longitude)
let query = geoFire.queryAtLocation(center, withRadius: radius)
query.observeEventType(.KeyEntered, withBlock: { (key: String!, location: CLLocation!) in
print("Key '\(key)' entered the search area and is at location '\(location)'")
})
query.observeReadyWithBlock({
//終了時の処理...
})
Not a valid geo location for a huge radiusエラー
位置検索で検索半径を23km以上に設定すると
Not a valid geo location for a huge radius
というエラーが発生するので、検索範囲を23km以内にしておくこと
もしパフォーマンスが劣化したら、、