Search code examples
iphoneannotationsmkmapviewmkannotationmapkit

How to add Different Images to Annotations in same Map View


I have A MapView with Multiple annotations. But I need to put different images to annotations according to JSON value.

enter image description here

This is what I want to do... Need to add Different Images to pins according to the JSON value.

is there any one has a idea how to do that? Please help and that would be very helpful.

Thanks


Solution

  • You can use the delegate method:

    -(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id )annotation

    and according to your JSON values you can set the image: The below is my sample code:

    UIImage * flagImage = nil;
    
    if(Your JSON Values)
    flagImage = [UIImage imageNamed:@"darkgreendot.png"];
    else if(....)
    flagImage = [UIImage imageNamed:@"orangedot.png"];
    else
    flagImage = [UIImage imageNamed:@"bluedot.png"];
    
    CGRect resizeRect;  
            resizeRect.size = flagImage.size;   
            resizeRect.origin = (CGPoint){0.0f, 0.0f};
            UIGraphicsBeginImageContext(resizeRect.size);
            [flagImage drawInRect:resizeRect];
            UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();    
            annotationView.image = resizedImage;