swiftmkmapviewios11mkannotationmkannotationview

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


I'm trying to work with the new features added to the mapview in ios11.

I'm clustering all my MKAnnotationView with circle collision but I have to check in real time when the annotation becomes clustered.

I have no idea how to do that.

EDIT (4/1/2018) :

More informations : When I select an annotation I add a custom CallOutView when the didSelect method is called and remove the CallOut when the didDeselect method is called.

The issue is when an annotation is selected and becomes clustered, when you zoom in the annotation is still selected but in "normal" state.

I want to remove the CallOut of my selected annotation when it become clustered like the didDeselect method.

Below screenshot to illustrate my issue :

1 - Annotation Selected

2 - Annotation Clustered

3 - Annotation Zoom In after cluster

I think it's just an issue of comprehension.

Any help would be really appreciated. Thank you in advance


Solution

  • 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
                 }
             }
         }
    
         //...
     }