Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to learn MapKit and am now trying to add an image as an overlay to the map view. I can't seem to find any sample code to help explain how to do this.

Can you guys please help me how to create MKOverlays and add them to MKMapKit.

Thanks in advance..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
568 views
Welcome To Ask or Share your Answers For Others

1 Answer

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...