如何使用Firestore从我的位置获取附近的用户(从Firebase数据库)?

时间:2020-05-07 05:44:24

标签: ios swift iphone xcode google-cloud-firestore

在我的Firestore数据库中,我有一个users表,其中包含具有详细信息及其GeoPoint的用户。

我想通过检查数据库中的用户是否在我的范围内,使用户在我的GMSCoordinateBounds位置附近。

有关该问题的更多查询评论。

当前我正在做的是,但没有得到正确的结果:-

    let visibleRegionn = mapView.projection.visibleRegion()
    let bounds = GMSCoordinateBounds(region: visibleRegionn)
    // we've got what we want, but here are NE and SW points
    let northEast = bounds.northEast
    let southWest = bounds.southWest

    let geopoint1 = GeoPoint(latitude: northEast.latitude, longitude: northEast.longitude)
    let geopoint2 = GeoPoint(latitude: southWest.latitude, longitude: southWest.longitude)


    let docRef = Firestore.firestore().collection("Users")
    let query =
        docRef
        .whereField("locationGeopoint", isLessThanOrEqualTo: geopoint1)
        .whereField("locationGeopoint", isLessThanOrEqualTo: geopoint2)

    query.getDocuments { snapshot, error in
        if let error = error {
            print("Error getting documents: \(error)")
        } else {
            for document in snapshot!.documents {
                self.arrListMapData.append(document.data() as NSDictionary)
            }

       }
    }

1 个答案:

答案 0 :(得分:2)

我认为代码可能正在工作,但是您的代码中可能存在逻辑错误。

let visibleRegionn = mapView.projection.visibleRegion()
let bounds = GMSCoordinateBounds(region: visibleRegionn)
// we've got what we want, but here are NE and SW points
let northEast = bounds.northEast
let southWest = bounds.southWest

let geopoint1 = GeoPoint(latitude: northEast.latitude, longitude: northEast.longitude)
let geopoint2 = GeoPoint(latitude: southWest.latitude, longitude: southWest.longitude)


let docRef = Firestore.firestore().collection("Users")
let query =
    docRef
    .whereField("locationGeopoint", isLessThan: geopoint1)
    .whereField("locationGeopoint", isGreaterThan: geopoint2)

query.getDocuments { snapshot, error in
    if let error = error {
        print("Error getting documents: \(error)")
    } else {
        for document in snapshot!.documents {
            self.arrListMapData.append(document.data() as NSDictionary)
        }

   }
}

如果看到两个地方都有-isLessThanOrEqualTo,则实际上不会给您正确的结果。您需要一个范围,因此现在您要查找该范围附近的所有用户,因此需要使用-isLessThanisGreaterThan之类的东西。

希望这会有所帮助!