如何检查注释是否聚集(MKMarkerAnnotationView 和 Cluster)

How to check if annotation is clustered (MKMarkerAnnotationView and Cluster)

我正在尝试使用 ios11 中添加到地图视图的新功能。

我正在将我的所有 MKAnnotationView 聚类为圆形碰撞,但我必须在注释变为聚类时实时检查。

我不知道该怎么做。

编辑(2018 年 4 月 1 日):

更多信息:当我 select 注释时,我在调用 didSelect 方法时添加自定义 CallOutView,并在调用 didDeselect 方法时删除 CallOut。

问题是当注释被 selected 并变成集群时,当您放大注释时仍然 selected 但处于 "normal" 状态。

当我的 selected 注释像 didDeselect 方法那样聚集时,我想删除它的 CallOut。

下面的截图说明了我的问题:

1 - Annotation Selected

2 - Annotation Clustered

3 - Annotation Zoom In after cluster

我觉得只是理解的问题

任何帮助将不胜感激。 提前谢谢你

当一个新的集群形成时,mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?将被调用以请求该集群的新视图。

你可以这样检查:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    //...
    if annotation is MKClusterAnnotation {
        //This is your new cluster.
    }
    //Alternatively if you need to use the values within that annotation you can do
    if let cluster = annotation as? MKClusterAnnotation {

    }
    //...
}

在iOS11中,Apple还在MKMapViewDelegate中引入了一个新的回调:

func mapView(_ mapView: MKMapView, clusterAnnotationForMemberAnnotations memberAnnotations: [MKAnnotation]) -> MKClusterAnnotation

在注释成为集群之前,将调用此函数为 memberAnnotations 请求 MKClusterAnnotation。所以名为memberAnnotations的第二个参数表示要聚类的注释。

编辑(2018 年 4 月 1 日):

聚类标注有两个关键步骤:

首先,在注释成为集群之前,MapKit 调用 mapView:clusterAnnotationForMemberAnnotations: 函数为 memberAnnotations.

请求 MKClusterAnnotation

其次,MapKit将MKClusterAnnotation添加到MKMapView,然后调用mapView:viewForAnnotation:函数生成MKAnnotationView。

因此您可以在两个步骤中的任何一个中取消选择注释,如下所示:

var selectedAnnotation: MKAnnotation? //the selected annotation

 func mapView(_ mapView: MKMapView, clusterAnnotationForMemberAnnotations memberAnnotations: [MKAnnotation]) -> MKClusterAnnotation {
     for annotation in memberAnnotations {
         if annotation === selectedAnnotation {
             mapView.deselectAnnotation(selectedAnnotation, animated: false)//Or remove the callout
         }
     }

     //...
 }

或:

 func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
     if let clusterAnnotation = annotation as? MKClusterAnnotation {
         for annotation in clusterAnnotation.memberAnnotations {
             if annotation === selectedAnnotation {
                 mapView.deselectAnnotation(selectedAnnotation, animated: false)//Or remove the callout
             }
         }
     }

     //...
 }

我来晚了两年,但只是想说你也可以通过以下方式检测是否选择了一个集群或一个单独的注释:

        func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {

            // selected annotation belongs to a cluster
            if view.annotation is MKClusterAnnotation {
                print("selected a cluster")
            }
        }