Yurii Petrov
Yurii Petrov

Reputation: 341

How to get count of markers visible on a MKMapView?

I'm using this code:

let annotationsInVisibleMapRect = self.mapView.annotations(in: mapView.visibleMapRect)
    let count = annotationsInVisibleMapRect.reduce(0) { (count, object) -> Int in
        if let cluster = object as? MKClusterAnnotation {
            if let view = self.mapView.view(for: cluster), !view.isHidden {
                return count + cluster.memberAnnotations.count
            }
        } else if let annotation = object as? MKCustomAnnotation {
            if let view = self.mapView.view(for: annotation), !view.isHidden {
                return count + 1
            }
        }
    }

But this code doesn't work correct. Sometimes I see cluster on the map, but this line

if let view = self.mapView.view(for: cluster) , !view.isHidden...

is giving isHidden equal true. I get wrong count as a result.

Upvotes: 0

Views: 267

Answers (1)

Fernand
Fernand

Reputation: 103

mapView.annotations.filter({ self.mapView.visibleMapRect.contains(MKMapPoint($0.coordinate)) }).count

Tested, worked for me :)

Upvotes: 1

Related Questions