从地图中删除注释 - Swift

Remove annotation from Map - Swift

我有麻烦了。我为包含 "identifier" 的 MKPointAnnotation 创建了自定义 class。

现在我想比较标识符,如果两个标识符相同,我想删除注释。

目前我有这段代码正在检查 annotation.title 和 user.username 是否相同,但我希望将其更改为:annotation.identifier 和 user.id.

 for annotation in self.mapView.annotations {
                    if let title = annotation.title, title == user.username {
                        self.mapView.removeAnnotation(annotation)
                    }

                }

注释的自定义class如下:

   class MyAnnotation: MKPointAnnotation {

    var identifier: String!
}

以及对于注释的创建:

let annotation = MyAnnotation()
                    annotation.title = user.username
                    annotation.subtitle = user.job
                    annotation.identifier = user.email
                    annotation.coordinate = CLLocationCoordinate2D(latitude: (Double(user.latitude ?? "0"))!, longitude: (Double(user.longitude ?? "0"))!)

                    self.mapView.addAnnotation(annotation)

在执行代码之前,您必须将注释转换为 MyAnnotation。尝试这样的事情:


 for annotation in self.mapView.annotations {
      if let annotation = annotation as? MyAnnotation, annotation.identifier == user.id {
          self.mapView.removeAnnotation(annotation)
      }
 }

希望对您有所帮助。