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

后端 未结 4 1385
甜味超标
甜味超标 2020-12-02 21:22

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.

Ca

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 22:16

    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  {
    
    }
    
    - (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 )overlay {
    
        MapOverlay *mapOverlay = overlay;
        MapOverlayView *mapOverlayView = [[[MapOverlayView alloc] initWithOverlay:mapOverlay] autorelease];
    
        return mapOverlayView;
    
    }
    

    Hope it helps!

提交回复
热议问题