iOS 8 SDK, Swift, MapKit Drawing a Route

百般思念 提交于 2019-12-10 20:45:09

问题


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
}


来源:https://stackoverflow.com/questions/25542085/ios-8-sdk-swift-mapkit-drawing-a-route

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!