如何只删除MapKit上的某种注释?

时间:2018-11-04 17:05:53

标签: swift mapkit mkannotation mkannotationview

在我的地图中,我有两种注释,一种是自定义注释,另一种是标准注释。我需要分别在地图中进行更新,因此当我遍历自定义项时,我不想干扰其他项。

这是我注册注释的代码:

map.register(customAnnotation.self, forAnnotationViewWithReuseIdentifier: "customAnnotation")
map.register(MKPointAnnotation.self, forAnnotationViewWithReuseIdentifier: "standardAnnotation")

和委托方法:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    if annotation is MKUserLocation {
        return nil
    }
    let annotation = mapkitView.dequeueReusableAnnotationView(withIdentifier: "customAnnotation") as! customAnnotation
    return annotation
}

这是更新注释位置的功能:

@objc func updateFireMarkersOnMap(){
    print("data count:",fireData.count)
    for annot in mapkitView.annotations {
        if annot.isEqual(customAnnotation.self) {print("custom annotation found")}
        mapkitView.removeAnnotation(annot)
    }

    for data in fireData {
        let annotation = MKPointAnnotation()
        annotation.coordinate = CLLocationCoordinate2D(latitude: CLLocationDegrees(data.lat), longitude: CLLocationDegrees(data.long))
        mapkitView.addAnnotation(annotation)
    }
}

在此功能中,我希望它将打印350次“找到的自定义注释”(我在地图上具有的注释数)。它从不打印此行。我尝试使用if annot is customAnnotationannot.iskind()isMember(),但是这些都不起作用。如何确定我要处理的注释?

从API提取位置数据后,我将删除所有注释,然后再次添加它们,但是我有两个来源,我无法将它们混合在一起,所以需要分别处理。

当我更新一种注释时,我无法删除其他注释。

我在这里想念什么?

1 个答案:

答案 0 :(得分:0)

我认为这就是您要寻找的。由于括号对齐,所有注释都会一直删除,这可以在批处理语句中完成

let annots = mapkitView.annotations
mapkitView.removeAnnotations(annots)

但这也可以工作。

  @objc func updateFireMarkersOnMap(){
        print("data count:",fireData.count)
        for annot in mapkitView.annotations {
            if annot is customAnnotation { print("custom annotation found") }
            mapkitView.removeAnnotation(annot)
        }

        for data in fireData {
            let annotation = MKPointAnnotation()
            annotation.coordinate = CLLocationCoordinate2D(latitude: CLLocationDegrees(data.lat), longitude: CLLocationDegrees(data.long))
            mapkitView.addAnnotation(annotation)
        }
    }