首页 > 解决方案 > 如何仅删除 MapKit 上的某种注释?

问题描述

在我的地图中,我有两种注释,一种是自定义的,一种是标准的。我需要分别在我的地图中更新它们,所以当我循环浏览自定义的时,我不想干扰另一个。

这是我注册注释的代码:

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 customAnnotation, annot.iskind()isMember()但这些都不起作用。如何识别我正在处理的注释?

在从 API 获取位置数据后,我将删除所有注释并再次添加它们,但我有两个来源,我无法将它们混合在一起,因此我需要单独处理它们。

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

我在这里想念什么?

标签: swiftmapkitmkannotationmkannotationview

解决方案


我想这就是你要找的。由于您的括号对齐,所有注释将一直被删除,这可以在批处理语句中完成

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)
        }
    }

推荐阅读