iphoneiosmkmapview

How do you check if an MKAnnotation is available within a MKCoordinateRegion


I've noticed that if I use MKMapView's selectAnnotation:animated:, that it will scroll my map off screen if the MKAnnotation is not displayed in the current MKCoordinateRegion that my map is displaying.

Is there a trivial way to check if an annotation is currently on screen within the specified MKCoordinateRegion? I'd like to be able to select an annotation that's only on screen and not something offscreen.


Solution

  • Use the annotationsInMapRect: method in the MKMapView class. It returns a NSSet of all annotation objects that are visible in the given map rect. Use the containsObject: method of NSSet to test if the annotation is present in that set of visible annotations.

    MKMapRect visibleMapRect = aMapView.visibleMapRect;
    NSSet *visibleAnnotations = [aMapView annotationsInMapRect:visibleMapRect];
    BOOL annotationIsVisible = [visibleAnnotations containsObject:someAnnotation];
    

    Also visibleMapRect is same as the region but just a different form of representation. Take from the docs,

    visibleMapRect

    The area currently displayed by the map view.

    @property(nonatomic) MKMapRect visibleMapRect

    This property represents the same basic information as the region property but specified as a map rectangle instead of a region.