Reputation: 751
I need to count number of annotations when i zooming mapView, and get array with which are shown on map, and then, i need to reload my Table and show list of only which shown on map.
How can i get number and array with annotation?
Upvotes: 10
Views: 5330
Reputation: 1588
David's great solution in Swift 4
extension MKMapView {
func visibleAnnotations() -> [MKAnnotation] {
return self.annotations(in: self.visibleMapRect).map { obj -> MKAnnotation in return obj as! MKAnnotation }
}
}
Upvotes: 4
Reputation: 2862
As for swift 2.0, I usually use this mapView extension to get all currently visible annotations as an array of MKAnnotations:
extension MKMapView {
func visibleAnnotations() -> [MKAnnotation] {
return self.annotationsInMapRect(self.visibleMapRect).map { obj -> MKAnnotation in return obj as! MKAnnotation }
}
}
Upvotes: 13
Reputation: 11607
How about these two methods from MapKit class:
1) Get visible rectangle of map using:
@property(nonatomic, readonly) CGRect annotationVisibleRect
2) Then get annotation NSSet from parameter map rectangle:
- (NSSet *)annotationsInMapRect:(MKMapRect)mapRect
So I would expect something like this:
-(void)getAnotationsInVisibleMapRectangle
{
NSSet *annotationSet = [myMapView annotationsInMapRect:myMapView.annotationVisibleRect];
// print number of annotations
NSLog(@"Number of annotations in rect: %d", annotationSet.count);
// this will return an array from the NSSet
NSArray *annotationArray = [annotationSet allObjects];
}
Does that help?
Upvotes: 10