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)
希望能帮助到你!