How to save the selected MKAnnotation?

I have an application that has a mapview and it displays 20 contacts (from an array) on the map. When the user taps on it, it can display a bubble with the right accessory button. Here's my problem: how do I know which pin was pressed? I heard something about the mapView: didSelectAnnotationView method, but I really don't understand how you get the pin / callout index so that I can get the information about the object at the same index of my array? Thanks for any help!


source to share

2 answers

When this method is called - because your viewController class accepted MKMapViewDelegate

, you can call -indexOfObject

on an array and get the index of that pin (annotation). This is due to the assumption that your array contains objects of the annotation class type.

- (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];


If you need more explanation, we need to know how you add these contacts i.e. implementation - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation




Here is a similar solution for Canopus.

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
    if ([view.annotation isKindOfClass:[MyAnnotation class]]) 
        NSInteger index = [mapView.annotations indexOfObject:view.annotation];


Note. I manually added annotations to the map and looked at their respective indices. They are not indexed in the order they are added to the mapView. those. just because you added the annotation as the fourth annotation, it could be index 1 or 3 or whatever. Someone has an explanation, but so far it has eluded me. Hope this helps.



All Articles