Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom image for MKAnnotation

I have created an annotation which I'm adding to an MKMapView. How would I go about having a custom image instead of the standard red pin?

@interface AddressAnnotation : NSObject<MKAnnotation> {
    CLLocationCoordinate2D coordinate;
    NSString *title;
    NSString *subtitle;
    MKPinAnnotationColor pinColor;
}
@property (nonatomic,retain) NSString *title;
@property (nonatomic,retain) NSString *subtitle;
@property (nonatomic, assign) MKPinAnnotationColor pinColor;
@end
like image 763
3sl Avatar asked Sep 18 '11 12:09

3sl


2 Answers

MKMapView gets its pin views from its delegate method mapView:viewForAnnotation: So you have to:

  1. Set your view controller as the map's delegate.
  2. Implement mapView:viewForAnnotation: in your controller.

Set your controller as delegate

@interface MapViewController : UIViewController <MKMapViewDelegate>

Mark the interface with the delegate protocol. This let's you set the controller as MKMapView's delegate in Interface Builder (IB). Open the .xib file containing your map, right click the MKMapView, and drag the delegate outlet to your controller.
If you prefer to use code instead IB, add self.yourMapView.delegate=self; in the controller's viewDidLoad method. The result will be the same.

Implement mapView:viewForAnnotation:

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
    // this part is boilerplate code used to create or reuse a pin annotation
    static NSString *viewId = @"MKPinAnnotationView";
    MKPinAnnotationView *annotationView = (MKPinAnnotationView*) 
        [self.mapView dequeueReusableAnnotationViewWithIdentifier:viewId];
    if (annotationView == nil) {
        annotationView = [[[MKPinAnnotationView alloc] 
            initWithAnnotation:annotation reuseIdentifier:viewId] autorelease];
    }
    // set your custom image
    annotationView.image = [UIImage imageNamed:@"emoji-ghost.png"];
    return annotationView;
}
like image 190
Jano Avatar answered Nov 08 '22 02:11

Jano


Override the mapView:viewForAnnotation: delegate method. If the annotation param points to one of your custom annotations, return a custom view that looks to your liking.

like image 41
Ole Begemann Avatar answered Nov 08 '22 04:11

Ole Begemann