iOS 8 SDK, Swift, MapKit Drawing a Route

2019-07-04 08:26发布

问题:

I need to draw route between two points and I'm using MKDirectionsRequest for my purpose.

Getting a route is OK, but I have trouble with drawing it.

In iOS 8 SDK there's no function

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay 

There is only this one:

func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer!

And for some reason, I can't understand why that method isn't called.
Delegate for MapView is set and MapKit is imported.


Here is the rendererForOverlay function that is implemented:

func rendererForOverlay(overlay: MKOverlay!) -> MKOverlayRenderer! {
    println("rendererForOverlay");

    var overlayRenderer : MKOverlayRenderer = MKOverlayRenderer(overlay: overlay);

    var overlayView : MKPolylineRenderer = MKPolylineRenderer(overlay: overlay);
    view.backgroundColor = UIColor.blueColor().colorWithAlphaComponent(0.5);

    return overlayView;
}


回答1:

The map view isn't calling your rendererForOverlay method because it is not named correctly.

The method must be named exactly:

mapView(mapView:rendererForOverlay)

but in your code it's named:

rendererForOverlay(overlay:)


In addition, you should check that the type of the overlay argument is MKPolyline and set the strokeColor of the polyline renderer.

(The view.backgroundColor in the existing code is actually changing the background color of the view controller's view -- not the polyline.)

Example:

func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
    println("rendererForOverlay");

    if (overlay is MKPolyline) {
        var pr = MKPolylineRenderer(overlay: overlay);
        pr.strokeColor = UIColor.blueColor().colorWithAlphaComponent(0.5);
        pr.lineWidth = 5;
        return pr;
    }

    return nil
}