Rakesh Thummar Rakesh Thummar - 4 months ago 19x
iOS Question

How to set image on MKAnnotation in MKMapView

I am developing an app for chating, I have to display all friends on a Map with their image.
Please provide guidance to implement it.

I have used following code...

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

MKPinAnnotationView *annView = [[MKPinAnnotationView alloc]init];
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Done.png"]];

annView.animatesDrop = TRUE;
annView.canShowCallout = YES;
annView.calloutOffset = CGPointMake(-5, 5);
[annView addSubview:imageView];
return annView;



enter image description here

What you are doing wrong is you are returning object of class MKPinAnnotationView, which is used for displaying pin-annotation.

You should use object of MKAnnotationView class. Then, customise it by changing its image:

annotationView.image = [UIImage imageNamed:@"friend_image.png"];

Now, you can get your friend's photo instead of default pin image.

Below is full code solving your problem:

  - (MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:(id <MKAnnotation>)annotation
        static NSString *annotationViewReuseIdentifier = @"annotationViewReuseIdentifier";

        MKAnnotationView *annotationView = (MKAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:annotationViewReuseIdentifier];

        if (annotationView == nil)
            annotationView = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:annotationViewReuseIdentifier] autorelease];

        // here you can assign your friend's image    
        annotationView.image = [UIImage imageNamed:@"friend_image.png"];
        annotationView.annotation = annotation;

        // add below line of code to enable selection on annotation view
        annotationView.canShowCallout = YES

        return annotationView;