Skip to content

Commit 776f76c

Browse files
authored
Merge pull request #16 from hyperoslo/fix/unclusted
Unclustering
2 parents bf3d4d3 + c6b1a79 commit 776f76c

File tree

1 file changed

+22
-5
lines changed

1 file changed

+22
-5
lines changed

Sources/ClusteringManager.swift

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,13 @@ public final class ClusteringManager {
55

66
public typealias Completion = (MKMapView) -> Void
77

8+
/// Return false for those annotations you don't want to be clustered
89
public var filterAnnotations: (MKAnnotation) -> Bool = { _ in return true }
910
private let rootNode: QuadTreeNode = QuadTreeNode(rect: MKMapRectWorld, capacity: 8)
11+
12+
/// These annotations are not being clustered
13+
/// They are rendered as is
14+
private var unclusteredAnnotations = [MKAnnotation]()
1015
private let lock = NSRecursiveLock()
1116

1217
public init(annotations: [MKAnnotation] = []) {
@@ -27,11 +32,16 @@ public final class ClusteringManager {
2732

2833
public func replace(annotations: [MKAnnotation]) {
2934
removeAll()
30-
add(annotations: annotations)
35+
36+
unclusteredAnnotations.append(
37+
contentsOf: annotations.filter({ !filterAnnotations($0) })
38+
)
39+
add(annotations: annotations.filter(filterAnnotations))
3140
}
3241

3342
public func removeAll() {
3443
rootNode.removeAll()
44+
unclusteredAnnotations.removeAll()
3545
}
3646

3747
public func renderAnnotations(onMapView mapView: MKMapView, completion: Completion? = nil) {
@@ -47,8 +57,16 @@ public final class ClusteringManager {
4757
return
4858
}
4959

50-
let annotations = strongSelf.clusteredAnnotations(tile: tile, scaleFactor: scaleFactor)
51-
strongSelf.reload(annotations: annotations, onMapView: mapView, completion: completion)
60+
let annotations = strongSelf.clusteredAnnotations(
61+
tile: tile,
62+
scaleFactor: scaleFactor
63+
)
64+
65+
strongSelf.reload(
66+
annotations: annotations + strongSelf.unclusteredAnnotations,
67+
onMapView: mapView,
68+
completion: completion
69+
)
5270
}
5371
}
5472

@@ -132,8 +150,7 @@ public final class ClusteringManager {
132150
// Add only the annotations we need in the current region
133151
// https://robots.thoughtbot.com/how-to-handle-large-amounts-of-data-on-maps#adding-only-the-annotations-we-need
134152
private func reload(annotations: [MKAnnotation], onMapView mapView: MKMapView, completion: Completion?) {
135-
let mapAnnotations = mapView.annotations.filter(filterAnnotations)
136-
let currentSet = NSMutableSet(array: mapAnnotations)
153+
let currentSet = NSMutableSet(array: mapView.annotations)
137154
let newSet = NSSet(array: annotations) as Set<NSObject>
138155

139156
// Remove user location

0 commit comments

Comments
 (0)