Search code examples
iphonemapkitcallout

How to show a call out for object that implements MkAnnotation protcol ?


I have an object that implements the MKAnnotation protocol:

#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
@interface VoiceMemoryAnnotation : NSObject <MKAnnotation> {
    NSString * blobkey;
}
@property (nonatomic, retain) NSString * blobkey;

-(id)initWithBlobkey:(NSString *) key andCoordinate:(CLLocationCoordinate2D) c;
@end

Adding this object a map works perfectly since I can see the red pins being dropped. However, the problem arises when I want to set this object to show a callout.

I cannot do annotation.showCallOut=YES because an "MkAnnotation" does not have this property, but a MkAnnotationView does. How do I get around this?

I tried to implement the map callback "viewForAnnotation" to check for "VoiceMemoryAnnotation" and I try to return a new "MkAnnotationView" and set it's callout = YES, but I start to get a segmentation fault when I do this.

Any ideas what I"m doing wrong?


Solution

  • First you need to create your annotation object (the one that implements the MKAnnotation protocol) and add it to your map using something like

    VoiceMemoryAnnotation*VMA = [[VoiceMemoryAnnotation alloc] init];
    VMA.title = @"Title String";
    VMA.subtitle = @"Subtitle String";
    
    [self.mapView addAnnotation:VMA];
    

    That will automatically call the following method which you will need to implement:

    - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
     {
         MKPinAnnotationView*singleAnnotationView = [[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:nil];
         singleAnnotationView.canShowCallout = YES;
    
         return singleAnnotationView;
     }
    

    In this implementation MKAnnotationView won't work, it needs to be MKPinAnnotationView.