After first time, when user Zoom Out or Pans out then will fetch additions hotspots based on the region changes. In this scenario, mapview shows like 5 individual annotations overlapping each other and when I tap on the annotation it merge back and form a cluster annotation.
Registering Annotation View
Code Block Swift mapView.register(WifiAnnotationView.self, forAnnotationViewWithReuseIdentifier: WifiAnnotationView.reuseID) mapView.register(ClusterWifiAnnotationView.self, forAnnotationViewWithReuseIdentifier: ClusterWifiAnnotationView.reuseID)
SingleAnnotationView
Code Block Swift class SingleAnnotationView: MKAnnotationView { static let reuseID = "SingleAnnotationView" lazy var subTitleLabel: UILabel = { let subTitle = UILabel() subTitle.numberOfLines = 0 return subTitle }() override init(annotation: MKAnnotation?, reuseIdentifier: String?) { super.init(annotation: annotation, reuseIdentifier: reuseIdentifier) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func prepareForDisplay() { super.prepareForDisplay() displayPriority = .defaultLow canShowCallout = true subTitleLabel.text = "address goes here" detailCalloutAccessoryView = subTitleLabel image = UIImage(named: "icon") } }
ClusterAnnotationView
Code Block Swift class ClusterAnnotationView: MKAnnotationView { static let reuseID = "ClusterAnnotation" lazy var subTitleLabel: UILabel = { let subTitle = UILabel() subTitle.numberOfLines = 0 return subTitle }() override init(annotation: MKAnnotation?, reuseIdentifier: String?) { super.init(annotation: annotation, reuseIdentifier: reuseIdentifier) collisionMode = .circle centerOffset = CGPoint(x: 0, y: -10) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func prepareForDisplay() { super.prepareForDisplay() if let cluster = annotation as? MKClusterAnnotation { let totalWifi = cluster.memberAnnotations.count if totalWifi > 0 { image = UIImage(named: "cluster-icon") displayPriority = .defaultHigh } } } }
View for Annotation: MKMapview Delegate
Code Block Swift public func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { switch annotation { case is HotspotPoint: let view = mapView.dequeueReusableAnnotationView(withIdentifier: WifiAnnotationView.reuseID, for: annotation) view.clusteringIdentifier = "WifiAnnotationView" return view case is MKClusterAnnotation: return mapView.dequeueReusableAnnotationView(withIdentifier: ClusterWifiAnnotationView.reuseID, for: annotation) default: return nil } }
Every time we make backend call to fetch additional annotations or new annotations then we remove entire annotations and add the new set of annotations to MapView. Please find the code below for add/remove api
Code Block Swift mapView.removeAnnotations(mapview.annotations) mapView.addAnnotations([newAnnotations])
Please let what's is going wrong for cluster logic not working properly.