Search code examples
objective-ciosmkmapviewmkannotation

Get indexPath for mapView Annotation


I am loading a bunch of pins on a map using data from a plist. Here is how I get the data:

for (int i=0; i<self.dataArray.count; i++){

    NSDictionary *dataDictionary = [self.dataArray objectAtIndex:i];
    NSArray *array = [dataDictionary objectForKey:@"Locations"];

    for (int i=0; i<array.count; i++){

        NSMutableDictionary *dictionary = [array objectAtIndex:i];

        double latitude = [[dictionary objectForKey:@"Latitude"] doubleValue];
        double longitude = [[dictionary objectForKey:@"Longitude"] doubleValue];

        CLLocationCoordinate2D coord = {.latitude =
            latitude, .longitude =  longitude};
        MKCoordinateRegion region = {coord};

        MapAnnotation *annotation = [[MapAnnotation alloc] init];
        annotation.title = [dictionary objectForKey:@"Name"];

        NSString *cityState = [dictionary objectForKey:@"City"];
        cityState = [cityState stringByAppendingString:@", "];
        NSString *state = [dictionary objectForKey:@"State"];
        cityState = [cityState stringByAppendingString:state];
        annotation.subtitle = cityState;
        annotation.coordinate = region.center;
        [mapView addAnnotation:annotation];
    }
}

Now for every annotation, I have added a detailDisclosureButton. I want to show details for that particular location from the plist. The problem is I need the indexPath.section and indexPath.row.

How can I get the indexPath of the pin? Is there a way to find the indexPath of the dictionary the annotation title is populated from?


Solution

  • Instead of tracking the "section" and "row", I suggest storing a reference to the dictionary itself in the annotation object.

    In the MapAnnotation class, add a property to hold a reference to the source dictionary:

    @property (nonatomic, retain) NSMutableDictionary *sourceDictionary;
    

    When creating the annotation (in your existing loop), set this property along with the title, etc:

    annotation.sourceDictionary = dictionary;
    annotation.title = [dictionary objectForKey:@"Name"];
    

    Then in the detail button handler method (assuming you are using the calloutAccessoryControlTapped delegate method), you cast the annotation object to your class and you'll be able to access the original dictionary the annotation came from:

    MapAnnotation *mapAnn = (MapAnnotation *)view.annotation;
    NSLog(@"mapAnn.sourceDictionary = %@", mapAnn.sourceDictionary);