使用注释坐标删除注释

Dav*_*tin 1 mapkit ios firebase swift firebase-realtime-database

我正在使用Firebase将注释添加到mapView。这可以通过以下步骤完成:

 func getMarkers() {

    dbRef.observe(.value, with: { (snapshot) in

        for buildings in snapshot.children {

            let buildingsObject = Buildings (snapshot: buildings as! FIRDataSnapshot)

            let latDouble = Double(buildingsObject.latitude!)
            let lonDouble = Double(buildingsObject.longitude!)

            self.telephoneNumber = buildingsObject.number

            let annotation = myAnnotationView.init(title: buildingsObject.content!, coordinate: CLLocationCoordinate2D.init(latitude: latDouble!, longitude: lonDouble!), duration: buildingsObject.duration!, cost: buildingsObject.cost!, info: "", timestamp: buildingsObject.timestamp, contactNumber: buildingsObject.number!, addedBy: buildingsObject.addedByUser!)

            self.mapView.addAnnotation(annotation)

            print (snapshot)

        }})}
Run Code Online (Sandbox Code Playgroud)

myAnnotationView是AnnotationView的自定义类。
向地图添加注释没有问题。问题在于,如果用户需要删除其注释,则需要将其从mapView中删除。我有一张桌子,上面有所有用户注释,如果他们愿意,他可以在其中删除。这将更新为Firebase控制台,并删除数据。但是,注释仍在地图上,仅当您重置应用程序时,注释才会更新。

我有一种方法来观察deleteChilds,它获得了正确的快照,但我似乎无法引用需要删除的注释。

func removeMarkers() {

    dbRef.observe(.childRemoved, with: { (snapshot) in

                        print (snapshot)

    })}
Run Code Online (Sandbox Code Playgroud)

被吐出来的快照在这里:

Snap (-KTo3kdGGA_-rfUhHVnK) { //childByAutoID
    addedByUser = TzDyIOXukcVYFr8HEBC5Y9KeOyJ2;
    content = "Post";
    cost = 500;
    duration = Monthly;
    latitude = "25.0879112000924";
    longitude = "55.1467777484226";
    number = 1234567890;
    timestamp = "Tue 11 Oct";
}
Run Code Online (Sandbox Code Playgroud)

所以我的问题是如何删除此快照中的注释?我可以以某种方式引用其坐标并以这种方式删除removeAnnotation吗?我浏览了Stack,但是其中大部分都提到了如何删除所有注释。

非常感谢。d

The*_*tor 5

MapKit具有removeAnnotation方法,可用于删除特定的注释。

在您的情况下,您需要一种比较坐标的方法。我们可以使用CLLocationCoordinate2D上的扩展名来做到这一点

extension CLLocationCoordinate2D: Hashable {
    public var hashValue: Int {
        get {
            // Add the hash value of lat and long, taking care of overlfolow. Here we are muliplying by an aribtrary number. Just in case.
            let latHash = latitude.hashValue&*123
            let longHash = longitude.hashValue
            return latHash &+ longHash
        }
    }
}

// Conform to the Equatable protocol.
public func ==(lhs: CLLocationCoordinate2D, rhs: CLLocationCoordinate2D) -> Bool {
    return lhs.latitude == rhs.latitude && lhs.longitude == rhs.longitude
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以从地图中获取所有注释,可以检查坐标是否匹配并删除。

        let allAnnotations = self.mapView.annotations
        for eachAnnot in allAnnotations{
            if eachAnnot.coordinate == <Your Coordinate>{
                self.mapView.removeAnnotation(eachAnnot)
            }
        }
Run Code Online (Sandbox Code Playgroud)