7.6. Displaying Custom Pins on a Map View

Problem

Instead of the default iOS SDK pins, you would like to display your own images as pins on a map view.

Solution

Load an arbitrary image into an instance of the UIImage class and assign it to the image property of the MKAnnotationView instance that you return to your map view as a pin:

- (MKAnnotationView *)mapView:(MKMapView *)mapView
            viewForAnnotation:(id <MKAnnotation>)annotation{

  MKAnnotationView *result = nil;

  if ([annotation isKindOfClass:[MyAnnotation class]] == NO){
    return result;
  }  if ([mapView isEqual:self.myMapView] == NO){
    /* We want to process this event only for the Map View
     that we have created previously */
    return result;
  }

  /* First typecast the annotation for which the Map View has
   fired this delegate message */
  MyAnnotation *senderAnnotation = (MyAnnotation *)annotation;

  /* Using the class method we have defined in our custom
   annotation class, we will attempt to get a reusable
   identifier for the pin we are about to create */
  NSString *pinReusableIdentifier =
  [MyAnnotation
   reusableIdentifierforPinColor:senderAnnotation.pinColor];

  /* Using the identifier we retrieved above, we will
   attempt to reuse a pin in the sender Map View */
  MKPinAnnotationView *annotationView = (MKPinAnnotationView *)
  [mapView
   dequeueReusableAnnotationViewWithIdentifier:
   pinReusableIdentifier];

  if (annotationView == nil){
    /* If we fail to reuse a pin, then we will create one */
    annotationView =
    [[MKPinAnnotationView alloc]  initWithAnnotation: ...

Get iOS 6 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.