15

I have about 400 MKAnnotationView´s that loads simultaneously into the MKMapView.

I understand that this isn't any good, it is a little bit slow, and I want to do it the "correct" way.

I zoom my map by a center coordinate:

MKCoordinateSpan span;
span.latitudeDelta = 0.8;
span.longitudeDelta = 0.8;

MKCoordinateRegion region;
region.span = span;

region.center = self.selectedCounty.coordinate;

[mapView setRegion:region animated:TRUE]; 

I only want to load the annotations that could be visible in that region.

I have a custom MKAnnotation called simply "Annotation" with a CLLocationCoordinate2D- and title-property.

I simply want to load the annotation for the "visible area" on the MKMapView so not all the annotation loads at the same time. And when the "visible area" on the MKMapView changes, I of course want to load annotations for that area.

I know that MKMapView has a delegate method which runs when the region changes.

But how do I know what annotations I should load for that region?

Fernando Redondo
  • 1,557
  • 3
  • 20
  • 38

3 Answers3

36
MKMapRect visibleMapRect = mapView.visibleMapRect;
NSSet *visibleAnnotations = [mapView annotationsInMapRect:visibleMapRect];
Shmidt
  • 16,436
  • 18
  • 88
  • 136
21

http://developer.apple.com/library/ios/#documentation/MapKit/Reference/MapKitFunctionsReference/Reference/reference.html

MKMapRectContainsPoint will tell you if it is visible.

visibleCount = 0;
for (MyAnnotation *annotation in mapView.annotations) {
    if (MKMapRectContainsPoint(mapView.visibleMapRect, MKMapPointForCoordinate(annotation.coordinate)))
    {
        visibleCount++;
    }
}

I recommend doing this method on a background thread if you have a lot of annotations. but you can determine if it is visible in the map

The Lazy Coder
  • 11,560
  • 4
  • 51
  • 69
  • Thanks for the positive votes guys. I am glad this is helping people with their map applications. – The Lazy Coder Oct 19 '11 at 23:49
  • 2
    no, this is NOT the correct answer, it requires to check every annotation on the map, see the answer below, and apples documentation for the annotationsInMapRect method that says "This method is much faster than doing a linear search of the objects in the annotations property yourself.", annotationsInMapRect uses a tree to store and search for points. – Pizzaiola Gorgonzola Jun 04 '13 at 09:24
  • @TheLazyCoder in swift 3.0 I am using this method to get annotations self.annotations(in: self.visibleMapRect).map { obj -> MKAnnotation in return obj as! MKAnnotation } Which method is faster? the ContainsPoint or this method? – user3126427 Nov 19 '16 at 03:03
-2

You can get the map region span and center, and based on the locations of the annotations you could check if any annotation is inside that region... maybe it is implemented already in something like [mapview isAnnotationVisible]... but you'll have to check everyone of the annotations eventually...

Sergio Campamá
  • 746
  • 1
  • 7
  • 14