【问题标题】:How to get single dataBase reference from Firebase如何从 Firebase 获取单个数据库引用
【发布时间】:2017-09-18 12:57:10
【问题描述】:

我正在与 Firebase 共享和检索坐标,但是当我在控制台中打印它们时……我得到相同的坐标 3-4 次。 这对我的自定义标记图像文件产生了奇怪的影响。 如何仅从 Firebase 获取坐标一次?

这是我的代码:

var posts=[postStruct]()
var mapView : GMSMapView? = nil
var friendLocator : [Locator] = [Locator]() 

struct Locator {
    let name: String
    let long: CLLocationDegrees
    let lat: CLLocationDegrees
}

var latPass: Double!
var longPass: Double!
var fetchLat: Double!
var fetchLong: Double!

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
    var location=locations[0]
    let span:MKCoordinateSpan=MKCoordinateSpanMake(0.01, 0.01)
    var myLocation:CLLocationCoordinate2D=CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
    let region:MKCoordinateRegion=MKCoordinateRegionMake(myLocation, span)
    latPass=28.3217378
    longPass=75.6895935

    post()
    self.configureMapView()

    let dataBaseRef=FIRDatabase.database().reference()
    dataBaseRef.child("Raunak Trikha").queryOrderedByKey().observeSingleEvent(of: .childAdded, with: {(snapshot) in

        let postDict = snapshot.value as? [String : AnyObject] ?? [:]
        var fetchLat = postDict["lat"] as! Double
        var fetchLong = postDict["long"] as! Double

        let locator = Locator(name: "Raunak Trikha", long: fetchLong, lat: fetchLat)
        self.friendLocator.append(locator)
        self.locateFriend()
        print(fetchLat)
        print(fetchLong)
    })       
    manager.stopUpdatingLocation()

    self.view = mapView

}

func locateFriend() {
    for friend in friendLocator{
        let friendMarker = GMSMarker()
        friendMarker.position=CLLocationCoordinate2D(latitude: friend.lat, longitude: friend.long)
        friendMarker.title=friend.name
        friendMarker.map=mapView
        mapView?.selectedMarker=friendMarker
        if friend.name=="Virat Singh"{

            friendMarker.icon=UIImage(named: "ViratPin.png")
        }

        else if friend.name=="Raunak Trikha"{

            friendMarker.icon=UIImage(named: "currentLocation.png")
        }
    }
    do {
        mapView?.mapStyle = try GMSMapStyle(jsonString: kMapStyle)
    } catch {
        NSLog("One or more of the map styles failed to load. \(error)")
    }
}


func configureMapView(){
    let camera = GMSCameraPosition.camera(withLatitude: latPass, longitude: longPass, zoom: 10)
    self.mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
    view = mapView
    mapView?.settings.scrollGestures = true
    mapView?.settings.zoomGestures = true
    mapView?.settings.myLocationButton = true
    //mapView?.addSubview(searchBar)
    //mapView?.addSubview(searchSupporter)
    //mapView?.bringSubview(toFront: searchBar)

    for gesture in (mapView?.gestureRecognizers!)! {

        mapView?.removeGestureRecognizer(gesture)

    }

}

当我打印 fetchLatfetchLong 时,我得到了 4 次相同的坐标,这与我的自定义标记图像重叠,产生了奇怪的效果。

【问题讨论】:

    标签: ios swift google-maps firebase core-location


    【解决方案1】:

    由于您添加特定 Locator 结构的代码被多次调用,因此在将其添加到本地数组之前,请检查您的数组以确保它不包含完全相同的结构。

    这将评估您的结构数组并确定它是否没有价值。但它也假设结构的 name 属性是每个结构的唯一标识符,这可能不是你的情况。您也可以比较 filter 闭包中要确保不重复的任何值,即。 e. latlong

        let locator = Locator(name: "Raunak Trikha", long: fetchLong, lat: fetchLat)
        if self.friendLocator.filter({ $0.name == locator.name }).count == 0 {
           self.friendLocator.append(locator)  
        }
        self.locateFriend()
    

    【讨论】:

    • 它说在调用中缺少参数
    • 啊,忘了你不能正常使用contains structs,一秒钟我会用另一种方法更新我的代码。
    • 现在显示cannot call value of non-function type int
    • 在哪一行?我刚刚在操场上测试了这段代码,它对我有用
    • 这个if self.friendLocator.filter({ $0.name == locator.name }).count == 0
    【解决方案2】:

    每当您的位置更改/更新或直到 GPS 在您的位置稳定(预热)时,都会调用此函数 func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])

    我注意到您正在使用 firebase 单事件 obeserver 函数使用 .observeSingleEvent() 进行数据库更新,这是正确的,但是由于您已在上述 didUpdateLocations 函数中定义了调用,它将被多次调用。

    要么将对 Firebase 的调用移出函数,要么提供一些条件以仅调用 firebase 一次。即仅在位置变化超过 X 范围/距离等时更新。

    【讨论】:

    • 将此函数 dataBaseRef.child("Raunak Trikha").queryOrderedByKey().observeSingleEvent(of: .childAdded, with: {(snapshot) 移出 didUpdateLocations。如果您需要最后报告的 lat并 lng 将其存储在一个 var 中,您可以在 didUpdateLocaitons 函数之外检索和初始化您的定位器结构。
    • 对不起,我是地图和位置的新手,你能用代码解释一下吗?谢谢
    • 这可能会对您有所帮助。 stackoverflow.com/questions/22292835/… 虽然它是 OBJ-C,但是您应该了解设置标志或设置距离过滤器等的想法。
    猜你喜欢
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    • 2016-12-16
    • 2020-06-19
    • 2021-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多