iOS MapKit custom pins

Bahamut picture Bahamut · Aug 22, 2011 · Viewed 32.2k times · Source

How do I show images instead of pins in the map. So far I can only add pins on tap. A sample code of the .m would extremely help since i'm still new to iOS programming.

Answer

Robin picture Robin · Aug 22, 2011
#pragma mark -
#pragma mark MKMapView delegate
- (MKAnnotationView *)mapView:(MKMapView *)mapview viewForAnnotation:(id <MKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MKUserLocation class]])
        return nil;
    static NSString* AnnotationIdentifier = @"AnnotationIdentifier";
    MKAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationIdentifier];
    if(annotationView)
        return annotationView;
    else
    {
        MKAnnotationView *annotationView = [[[MKAnnotationView alloc] initWithAnnotation:annotation
                                                                         reuseIdentifier:AnnotationIdentifier] autorelease];
        annotationView.canShowCallout = YES;
        annotationView.image = [UIImage imageNamed:@"someImage.png"];
        UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        [rightButton addTarget:self action:@selector(writeSomething:) forControlEvents:UIControlEventTouchUpInside];
        [rightButton setTitle:annotation.title forState:UIControlStateNormal];
        annotationView.rightCalloutAccessoryView = rightButton;
        annotationView.canShowCallout = YES;
        annotationView.draggable = YES;
        return annotationView;
    }
    return nil;
 }

EDIT:

I could explain to you all about the MKAnnotationView, but I think you will find the documentation provided by Apple to be a far better explanation than from any other source. Check the overview section in the link.

https://developer.apple.com/documentation/mapkit/mkannotationview