如何创建图像叠加并添加到MKMapView?

Jr *_*nta 14 iphone cocoa-touch mkmapview

我正在尝试学习MapKit,现在我正在尝试将图像添加为地图视图的叠加层.我似乎无法找到任何示例代码来帮助解释如何执行此操作.

你们能帮助我如何创建MKOverlay并添加它们MKMapKit.

提前致谢..

Rap*_*sso 25

以下是如何将a UIImage设置为MKMapView叠加层的示例.一些参数(坐标和图像路径)是固定的,但我猜想代码可以很容易地改变.

创建一个符合以下条件的类MKOverlay:

MapOverlay.h

@interface MapOverlay : NSObject <MKOverlay> {

}

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

@end
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

创建一个符合MKOverlayView的类:

MapOverlayView.h

@interface MapOverlayView : MKOverlayView {

}

@end
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

将叠加层添加到MKMapView:

MapOverlay * mapOverlay = [[MapOverlay alloc] init];
[mapView addOverlay:mapOverlay];
[mapOverlay release];
Run Code Online (Sandbox Code Playgroud)

在mapView委托上,实现viewForOverlay:

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

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

    return mapOverlayView;

}
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你!


Mar*_*c W -2

仅从苹果的协议文档来看MKOverlay,它看起来并不是很复杂。只需创建一个类来执行计算覆盖所需的任何操作,并确保它符合该协议。这意味着您必须拥有coordinateboundingMapRect属性以及 的实现intersectsMapRect:。苹果文档解释了这一切。

看一下Apple 的HazardMap示例代码。它使用自定义叠加视图,就像您想要在叠加中显示图像一样。mapView:viewForOverlay:您只需在类中实现MKMapViewDelegate并返回子类的新实例MKOverlayView即可在屏幕上绘制自定义叠加层。