Overlays

An overlay differs from an annotation in being drawn entirely with respect to points on the surface of the earth. Thus, although an annotation’s size is always the same, an overlay’s size is tied to the zoom of the map view. (Overlays were introduced in iOS 4.)

Overlays are implemented much like annotations. You provide an object that adopts the MKOverlay protocol (which itself conforms to the MKAnnotation protocol) and add it to the map view. When the map view delegate method mapView:viewForOverlay: is called, you provide an MKOverlayView that actually draws the overlay. As with annotations, this architecture means that the overlay itself is a lightweight object, and the overlay view is needed only if the part of the earth that the overlay covers is actually being displayed in the map view.

Some built-in MKShape subclasses adopt the MKOverlay protocol: MKCircle, MKPolygon, and MKPolyline. MKOverlayView has subclasses MKCircleView, MKPolygonView, and MKPolylineView, ready to draw the corresponding shapes. Thus, as with annotations, you can base your overlay entirely on the power of existing classes.

In this example, I’ll use MKPolygonView to draw an overlay triangle pointing up the road from the parking place annotated in our earlier examples (Figure 34-4). We add the MKPolygon as an overlay to our map view, and derive the MKPolygonView from it in our implementation of mapView:viewForOverlay:. First, the MKPolygon overlay:

CLLocationCoordinate2D loc = self->map.region.center; ...

Get Programming iOS 4 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.