iOS Swift 获取两点之间的方向并绘制到地图

iOS Swift Getting directions between two points and drawing to map

我想获取两点之间的方向并将它们绘制到我的 MKMapView 中。这是我的实现:

首先,在我的控制器的 viewDidLoad 回调中,我将地图的视图委托设置为 self

map.delegate = self

然后,我请求所有路由:

func showDirections() {
        let currentPlace: MKPlacemark = MKPlacemark(coordinate: location.coordinate, addressDictionary: nil)
        let place: MKPlacemark = MKPlacemark(coordinate: annotation.coordinate, addressDictionary: nil)



    println(currentPlace.coordinate.latitude)
    println(currentPlace.coordinate.longitude)
    println(place.coordinate.latitude)
    println(place.coordinate.longitude)

    var request: MKDirectionsRequest = MKDirectionsRequest.new()
    request.setSource(MKMapItem(placemark: currentPlace))
    request.setDestination(MKMapItem(placemark: place))
    request.transportType = MKDirectionsTransportType.Any
    request.requestsAlternateRoutes = true
    var directions: MKDirections = MKDirections(request: request)
    directions.calculateDirectionsWithCompletionHandler() {
        (response, error) in
        println(error)
        if(error == nil && response != nil) {
            println("Numero de rutas: " + String(response.routes.count))
            println(response.routes[0].coordinate)
            for(var i = 0;i < response.routes.count; i++) {
                self.map.addOverlays(response.routes[i].overlays, level: MKOverlayLevel.AboveRoads)
                self.map.setNeedsDisplay()
            }
            for r in response.routes { println("route = \(r)") }
        }
    }

}

并实现这两个回调:

func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
        println("redenrerForOverlay")
        if(overlay.isKindOfClass(MKPolyline)) {
            var renderer: MKPolylineRenderer = MKPolylineRenderer(overlay: overlay)
            renderer.strokeColor = Colors.psnGreen
            renderer.lineWidth = 5
            return renderer
        }
        return nil
    }

func mapView(mapView: MKMapView!, viewForOverlay overlay: MKOverlay!) -> MKOverlayView! {
        println("ViewForOverlay")
        if (overlay.isKindOfClass(MKPolyline)) {
            var lineView: MKPolylineView = MKPolylineView(overlay: overlay)
            lineView.backgroundColor = Colors.psnGreen

            return lineView;
        }
        return nil;
    }

当我 运行 我的应用程序时,我有两条路线要绘制,但是当我调用 map.addOverlay 时,没有任何反应。我的 rendererForOverlay/viewForOverlay 从未被调用过。有人知道如何让它发挥作用吗?

提前致谢

我终于找到了解决方案

有兴趣的朋友,只需将路线回调更改为:

directions.calculateDirectionsWithCompletionHandler() {
            (response, error) in
            if(error == nil && response != nil) {
                for route in response.routes {
                    var r: MKRoute = route as! MKRoute
                    self.map.addOverlay(r.polyline, level: MKOverlayLevel.AboveRoads)
                }
            }
        }