How do I create an image overlay and add to MKMapView?

Here is an example to how to sets a UIImage to a MKMapView overlay. Some parameter (coordinates and image path) are fixed, but the code can be easily changed, I guess.

Create an class that conforms to MKOverlay:

MapOverlay.h

@interface MapOverlay : NSObject <MKOverlay> {

}

- (MKMapRect)boundingMapRect;
@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;

@end

MapOverlay.m

@implementation MapOverlay

- (id)initWithCoordinate:(CLLocationCoordinate2D)coordinate {
    self = [super init];
    if (self != nil) {


    }
    return self;
}

- (CLLocationCoordinate2D)coordinate
{
    CLLocationCoordinate2D coord1 = {
        37.434999,-122.16121
    };

    return coord1;
}

- (MKMapRect)boundingMapRect
{

    MKMapPoint upperLeft = MKMapPointForCoordinate(self.coordinate);

    MKMapRect bounds = MKMapRectMake(upperLeft.x, upperLeft.y, 2000, 2000);
    return bounds;
}


@end

Create an class that conforms to MKOverlayView:

MapOverlayView.h

@interface MapOverlayView : MKOverlayView {

}

@end

MapOverlayView.m

@implementation MapOverlayView

- (void)drawMapRect:(MKMapRect)mapRect
          zoomScale:(MKZoomScale)zoomScale
          inContext:(CGContextRef)ctx
{

    UIImage *image          = [[UIImage imageNamed:@"image.png"] retain];

    CGImageRef imageReference = image.CGImage;

    MKMapRect theMapRect    = [self.overlay boundingMapRect];
    CGRect theRect           = [self rectForMapRect:theMapRect];
    CGRect clipRect     = [self rectForMapRect:mapRect];

    CGContextAddRect(ctx, clipRect);
    CGContextClip(ctx);

    CGContextDrawImage(ctx, theRect, imageReference);

    [image release]; 

}


@end

Add the overlay to the MKMapView:

MapOverlay * mapOverlay = [[MapOverlay alloc] init];
[mapView addOverlay:mapOverlay];
[mapOverlay release];

On the mapView delegate, implement the viewForOverlay:

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay {

    MapOverlay *mapOverlay = overlay;
    MapOverlayView *mapOverlayView = [[[MapOverlayView alloc] initWithOverlay:mapOverlay] autorelease];

    return mapOverlayView;

}

Hope it helps!

Leave a Comment