I have a MKMapView with several annotations and 3 of them are very close to each other.
I used mapView.showAnnotations(mapView.annotations, animated: false) to display all annotations on the same region at launch but one of the 3 is hidden because it's too close.
I looked into Apple's Documentation but couldn't find a way to prevent this from happening, any idea how to prevent annotations grouping?
(I've never seen this before, maybe it's a iOS 11 feature)
What you are seeing ist not clustering (you had to write code to get a cluster and you would usually see a cluster)
My experiments appear to suggest...
MKAnnotationViewsare rendered from top to bottom of the map. (It doesn't matter where north is).MapKitdecides to draw overlappingMKAnnotationViews, then theMKAnnotationViewnearer to the bottom is drawn on top (because it's drawn later)MKAnnotationViews, also titles rendered belowMKMArkerAnnotationViewsneed space. The rendering of those titles is influenced bymarkerView.titleVisibility. IfmarkerView.titleVisibilityis set to.visible(instead of the default.adaptive), then this title is stronger than aMarkerAnnotationViewthat is rendered later, even if the laterMarkerAnnotationViewhas adisplayPriority = .required. TheMarkerAnnotationViewnearer to the bottom is not rendered.MarkerAnnotationViewnearer to the top has a lowdisplayPriority. So aMarkerAnnotationViewwith lowdisplayPriorityand.titleVisibility = .visiblecan make aMarkerAnnotationViewnearer to the bottom withdisplayPriority = .requireddisappear.So what should you do:
annotationView.displayPriority = .requiredfor all relevant annotations. (This is necessary but not sufficient)annotationView.titleVisibility = .visibleor the title will make annotationViews disappear that are rendered nearer the bottom. Instead setannotationView.titleVisibility = .adaptiveI don't think you can control the visibility completely. But the problem with
annotationView.titleVisibility = .visiblewas surprising for me and you should avoid it because it will hide annotations.Clusters behave like (and are) annotations that behave exactly as described above, if clusters are used.
Edit, a few years later:
Since iOS 14,
MKAnnotationViewhas two new variables:zPriorityhttps://developer.apple.com/documentation/mapkit/mkannotationview/3547913-zpriorityselectedZPriorityhttps://developer.apple.com/documentation/mapkit/mkannotationview/3547912-selectedzprioritySet a higher value to make sure the more important
MKAnnotationViewstays visible. This works nicely.For Annotations with the same
zPriority, the text above is still valid.Please be aware that Apple decided to make
zPrioritya property ofMKAnnotationViewand not ofMKAnnotation.This means as soon as MapKit decides to hide your favourite
MKAnnotationView, you can't set thezPriorityvariable any more since the view doesn't exit any more. I solve this by settingzPriorityimmediately after creation of theMKAnnotationView. This last paragraph is not in Apples documentation.