4

I have a really simple question: how can I check if an MKAnnotation is selected on a map?

I can't see a selected like (GET) property.

I hope the solution would not be by triggering selected/deselected events and store its result in a property and check them if I need. There must be a more straightforward one.

Thanks very much!

Tom
  • 3,899
  • 22
  • 78
  • 137

3 Answers3

6

Making use of the delegate method of MKMapView didSelectAnnotationView: use can get the event MKAnnotation Selected

-(void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {
    // Annotation is your custom class that holds information about the annotation
    if ([view.annotation isKindOfClass:[Annotation class]]) {
        Annotation *annot = view.annotation;
        NSInteger index = [self.arrayOfAnnotations indexOfObject:annot];
    }
}

Hope it will help you.

Gaurav Rastogi
  • 2,145
  • 1
  • 14
  • 19
  • I know that, thanks, but I am really shocked there is not a simple isSelected property for annotation... – Tom May 06 '13 at 17:15
  • 1
    There could be simple Selected Property is you add a custom button on to MKAnnotationView , otherwise you need to take help of this delegate method. – Gaurav Rastogi May 06 '13 at 17:18
6

Check out -[MKMapView selectedAnnotations].

incanus
  • 5,100
  • 1
  • 13
  • 20
1

Just an update to this -- in iOS 4 there are MKMapViewDelegate methods that can be used to track annotation selection and de-selection:

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
- (void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view

You can use an Observer for Selected annotation Event:

[pin addObserver:self
      forKeyPath:@"selected" 
         options:NSKeyValueObservingOptionNew
         context:@"ANSELECTED"];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{

    NSString *action = (NSString*)context;

    if([action isEqualToString:@"ANSELECTED"]){

        BOOL annotationAppeared = [[change valueForKey:@"new"] boolValue];
        if (annotationAppeared) {
            // clicked on an Annotation
        }
        else {
            // Annotation disselected
        }
    }
}
Nishant Tyagi
  • 9,893
  • 3
  • 40
  • 61