Search code examples
iosobjective-cannotationsmapkitreuseidentifier

Displaying two different annotation images


I would like to show 2 different types of annotations based on a specific 'chain' variable... How could I go about doing so? This is a code snippet I have now:

pinView = [[MKAnnotationView alloc] initWithAnnotation:annotation  
  reuseIdentifier:PharmacyPinID];

NSString *chainString = tmpAnnotation.chain;
NSString *mapImage = [NSString stringWithFormat:@"map_icon_%@",chainString];
pinView.image = [UIImage imageNamed:mapImage];

Thanks!


Solution

  • Right now you're using generic MKAnnotationView objects. What do you want to do differently?

    A short answer is to do something like this:

    MKAnnotationView *myAnnotationView;
    switch tmpAnnotation.type
    {
      case type1:
        myAnnotationView= [[CustomAnnoation1 alloc] initWithAnnotation:tmpAnnotation 
          reuseIdentifier: type1ID];
      case type2:
        myAnnotationView= [[CustomAnnoation2 alloc] initWithAnnotation:tmpAnnotation 
          reuseIdentifier: type2ID];
      default: 
       myAnnotationView= [[MKAnnotationView alloc] initWithAnnotation:tmpAnnotation  
         reuseIdentifier:PharmacyPinID];
    }
    NSString *chainString = tmpAnnotation.chain;
    NSString *mapImage = [NSString stringWithFormat:@"map_icon_%@",chainString];
    pinView.image = [UIImage imageNamed:mapImage];
    

    The code above assumes that tmpAnnotation is a custom type that has a property type that tells you what kind of annotation view you want. (An annotation is any object you want that conforms to the MKAnnotation protocol, so it can have custom properties if you want.)

    It also assumes that you have several different custom subclasses of MKAnnotationView that you want to use.