Framework that clusters annotations on MKMapView
.
Based on https://github.com/ribl/FBAnnotationClusteringSwift.
NOTE: This project is deprecated since Apple has added native clustering support with iOS 11!
iOS 8.0+, Swift 3
An example app is included to demonstrate the usage of AnnotationClustering
.
Create an instance of the cluster manager.
let clusterManager = ClusterManager()
Create annotations and add them to the cluster manager.
clusterManager.addAnnotations(annotations)
clusterManager.delegate = self
Return cluster or pin in the delegate of the map view.
extension ViewController : MKMapViewDelegate {
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool){
OperationQueue().addOperation { [unowned self] in
let mapBoundsWidth = Double(mapView.bounds.size.width)
let mapRectWidth:Double = mapView.visibleMapRect.size.width
let scale:Double = mapBoundsWidth / mapRectWidth
let annotationArray = self.clusterManager.clusteredAnnotationsWithinMapRect(self.mapView.visibleMapRect, withZoomScale:scale)
self.clusterManager.displayAnnotations(annotationArray, mapView: mapView)
}
}
// Note: The example app doesn't support showing the user location. The handling of the user location pin is given as an example here in case your app wants to use it.
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
var reuseId = ""
switch annotation {
case is MKUserLocation:
return nil // show Apple's default user location pin
case let cluster as AnnotationCluster:
reuseId = "Cluster"
if let clusterView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? AnnotationClusterView {
clusterView.reuseWithAnnotation(cluster)
return clusterView
}
else {
let options = AnnotationClusterViewOptions(smallClusterImage: "cluster_2_30", mediumClusterImage: "cluster_2_40", largeClusterImage: "cluster_2_50")
return AnnotationClusterView(annotation: cluster, reuseIdentifier: reuseId, options: options)
}
default:
reuseId = "Pin"
if let pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView {
pinView.annotation = annotation
return pinView
}
else {
let pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
return pinView
}
}
}
}
You can find the API documentation here: Documentation
Add the following line to your Cartfile.
github "gunterhager/AnnotationClustering"
Then run carthage update
.
Just drag and drop the .swift
files in the AnnotationClustering
folder into your project.
AnnotationClustering
is available under the MIT license. See the LICENSE file for details.
Made with ❤ at all about apps.