Search code examples
objective-cimagemkmapviewmkannotationview

How to set multiple images for MKAnnotationViews?


I'm working on an app that makes use of the MapKit Classes Mkannotation and MKAnnotationView (Both subclassed, of course).

My question is, how can I put multiple FGAnnotationViews on my map (about 5) that all have different images?

I know that I could create 5 different new Classes and init the one matching, but I thought, that maybe there was a method to put an if statement inside the

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

function, like

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
MKAnnotationView *annView = nil;

if (annotation == myRestaurantAnnotation) {

    FGAnnotationView *fgAnnView = (FGAnnotationView*)[self.mapView dequeueReusableAnnotationViewWithIdentifier:@"Location"];
    fgAnnView = [[FGAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"Location"];
}
return annView;
}

Anyone?


Solution

  • You're almost there. Try this

    - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
        MKAnnotationView *annView = nil;
    
        FGAnnotationView *fgAnnView = (FGAnnotationView*)[self.mapView dequeueReusableAnnotationViewWithIdentifier:@"Location"];
    
        if (annotation == myRestaurantAnnotation) {
            fgAnnView.image = //MAGIC GOES HERE//;
        } else if (annotation == myBankAnnotation) {
            fgAnnView.image = //MAGIC GOES HERE//;
        }
        return fgAnnView;
    }
    

    If you are letting the map draw the user's location you should check the class of the annotation and make sure it isn't MKUserLocation. If it is then you return nil. If you have multiple instances of each annotation class you can use the class to determine the image to set rather than matching the object itself, like this:

    if ([annotation isKindOfClass:[MKUserLocation class]]) {
        return nil;
    } else if ([annotation isKindOfClass:[FGRestaurantAnnotation class]]) {
        fgAnnView.image = //YOUR IMAGE CODE//
    }