How do I show MKOverlay above MKAnnotations?

2019-02-17 04:29发布

问题:

I'm trying to use an MKOverlay (specifically an MKPolyline) to show a route on the map. However, I need the route to show up above my existing pins (custom MKAnnotationViews). Is there a good way to bring the MKPolyline to the front above the pins?

回答1:

It might be useful to investigate the annotation layer's zOrder property. Sending the annotations backwards in your superview's hierarchy may help you achieve the effect needed. Changing your annotation z-axis position should probably be done within the mapView:didAddAnnotationViews: delegate method.

- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views {
    annotationView.layer.zPosition = x;
}

It's been a while since I've dealt with MKPolyline, and I know things changed a lot in iOS 8, but you might be able to directly manipulate the polyline's z position while you're drawing it.


UPDATE
When you add your MKOverlay to the map, starting in iOS 7.0+, use the addOverlay:level: method. This allows you to specify the z-position of the overlay. One of the highest z-positions for the overlay as defined by MKOverlayLevels is MKOverlayLevelAboveLabels:

Place the overlay above map labels, shields, or point-of-interest icons but below annotations and 3D projections of buildings.

Unfortunately, as mentioned in the documentation above, the map does not support placing overlays above annotations. A possible solution may be to add the annotations to a separate MKOverlay object and then to add the other overlay (with the path) to the map using insertOverlay:aboveOverlay:.