Is there a way to add text using Paths Drawing

With MKOverlayPathView, I think the easiest way to add text is to override drawMapRect:zoomScale:inContext: and put the path and text drawing there (and do nothing in or don’t implement createPath).

But if you’re going to use drawMapRect anyway, you might want to just switch to subclassing a plain MKOverlayView instead of MKOverlayPathView.

With an MKOverlayView, override the drawMapRect:zoomScale:inContext: method and draw the circle using CGContextAddArc (or CGContextAddEllipseInRect or CGPathAddArc).

You can draw the text using drawAtPoint in this method which will have the required context.

For example:

-(void)drawMapRect:(MKMapRect)mapRect zoomScale:(MKZoomScale)zoomScale inContext:(CGContextRef)context
{
    //calculate CG values from circle coordinate and radius...
    CLLocationCoordinate2D center = circle_overlay_center_coordinate_here;

    CGPoint centerPoint = 
        [self pointForMapPoint:MKMapPointForCoordinate(center)];

    CGFloat radius = MKMapPointsPerMeterAtLatitude(center.latitude) * 
                         circle_overlay_radius_here;

    CGFloat roadWidth = MKRoadWidthAtZoomScale(zoomScale);

    //draw the circle...
    CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
    CGContextSetFillColorWithColor(context, [[UIColor blueColor] colorWithAlphaComponent:0.2].CGColor);
    CGContextSetLineWidth(context, roadWidth);
    CGContextAddArc(context, centerPoint.x, centerPoint.y, radius, 0, 2 * M_PI, true);
    CGContextDrawPath(context, kCGPathFillStroke);

    //draw the text...
    NSString *text = @"Hello";
    UIGraphicsPushContext(context);
    [[UIColor redColor] set];
    [text drawAtPoint:centerPoint 
             withFont:[UIFont systemFontOfSize:(5.0 * roadWidth)]];
    UIGraphicsPopContext();
}

In relation to a comment in another answer…

When the center coordinate or radius (or whatever) of the associated MKOverlay changes, you can make the MKOverlayView “move” by calling setNeedsDisplayInMapRect: on it (instead of removing and adding the overlay again). (When using a MKOverlayPathView, you can call invalidatePath instead.)

When calling setNeedsDisplayInMapRect:, you can pass the boundingMapRect of the overlay for the map rect parameter.

In the LocationReminders sample app from WWDC 2010, the overlay view uses KVO to observe changes to the associated MKOverlay and makes itself move whenever it detects a change to the circle’s properties but you could monitor the changes in other ways and call setNeedsDisplayInMapRect: explicitly from outside the overlay view.


(In a comment on another answer I did mention using MKOverlayPathView and that is how the LocationReminders app implements a moving circle overlay view. But I should have mentioned how you can also use MKOverlayView to draw a circle. Sorry about that.)

Leave a Comment