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

て烟熏妆下的殇ゞ 提交于 2019-12-03 03:56:05

In iOS 11, Apple also introduce a new callback in MKMapViewDelegate:

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

Before annotations become clustered, this function will be called to request a MKClusterAnnotation for memberAnnotations. So the second parameter named memberAnnotations indicates the annotations to be clustered.

EDIT (4/1/2018):

There are two key steps for cluster annotation:

First, before annotations become clustered, MapKit invoke mapView:clusterAnnotationForMemberAnnotations: function to request a MKClusterAnnotation for memberAnnotations.

Secondly, MapKit add the MKClusterAnnotation to MKMapView, and mapView:viewForAnnotation: function will be called to produce a MKAnnotationView.

So you can deselect annotation in either of the two steps, like this:

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

     //...
 }

Or:

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

     //...
 }

When a new cluster is formed, mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? will be called to request for a new view for that cluster.

You can do you check like this:

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 {

    }
    //...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!