Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C MapKit Overlay on entire map

How would I create an overlay that colors the entire map a certain color? Then I need to be able to place annotations on top of it. Any ideas? Thanks.

like image 900
Jacob R Avatar asked Mar 12 '14 17:03

Jacob R


1 Answers

What you want is MKOverlay and MKOverlayView. You can find apple's code in one of the apps mentioned in 'Related sample code'. in above protocol and class reference page.

EDIT : As Per the comments previous code was not working as-is. Heres a MKMapDimOverlay GitHub project which you can simply integrate using CocoaPods. I have also made the relevant changes in following code in the answer.

To explain briefly, following is code for adding a dark overlay on entire map.

You need to create an overlay and add it to the map view.

MKMapDimOverlay *dimOverlay = [[MKMapDimOverlay alloc] initWithMapView:MapView];
[mapView addOverlay: dimOverlay];

Create and return MKOverlayView for the specific MKOverlay in 'viewForOverlay' delegate method

-(MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay {
    if([overlay isMemberOfClass:[MKMapDimOverlay class]]) {
        MKMapDimOverlayView *dimOverlayView = [[MKMapDimOverlayView alloc] initWithOverlay:overlay];
        return dimOverlayView;
    }
}

Since all you want is a colored overlay covering the map, your overlay and overlay view implementation will be very simple.

DimOverlay.m

@interface DimOverlay ()
@property (nonatomic) CLLocationCoordinate2D dimOverlayCoordinates;
@end

@implementation DimOverlay

-(id)initWithMapView:(MKMapView *)mapView {
    self = [super init];
    if(self)
    {
        self.dimOverlayCoordinates = mapView.centerCoordinate;
    }
    return self;
}

-(CLLocationCoordinate2D)coordinate {
    return self.dimOverlayCoordinates;
}

-(MKMapRect)boundingMapRect {
    return MKMapRectWorld;
}

@end

DimOverlayView.m

@implementation DimOverlayView

- (void)drawMapRect:(MKMapRect)mapRect
          zoomScale:(MKZoomScale)zoomScale
          inContext:(CGContextRef)ctx {
    /*
     You can allow custom colors and opacity values.
     Simply add UIColor and CGFloat properties in the overlay view class 
     and use those properties instead of the default hardcodes values below.
    */
    CGContextSetAlpha(ctx, 0.85);
    CGContextSetFillColorWithColor(ctx, [UIColor blackColor].CGColor);
    CGContextFillRect(ctx, [self rectForMapRect:mapRect]);
}

@end
like image 110
Swapnil Luktuke Avatar answered Oct 22 '22 21:10

Swapnil Luktuke