Removing Annotation using the Annotations Coordinates

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-04 18:45:01

MapKit has removeAnnotation method, that can be used remove a specific annotation.

In your case you need to a way to compare coordinates. WE can do that using an extension on 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
}

Now, you can fetch all the annotations from the map, can check if any matches your co-ordinate & remove it.

        let allAnnotations = self.mapView.annotations
        for eachAnnot in allAnnotations{
            if eachAnnot.coordinate == <Your Coordinate>{
                self.mapView.removeAnnotation(eachAnnot)
            }
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!