使用mapkit Swift 3绘制多段线

使用mapkit Swift 3绘制多段线,swift,xcode,mapkit,draw,polyline,Swift,Xcode,Mapkit,Draw,Polyline,我想绘制从当前用户位置到注释点的多段线,但它似乎没有绘制任何内容: @IBAction func myButtonGo(_ sender: Any) { showRouteOnMap() } func showRouteOnMap() { let request = MKDirectionsRequest() request.source = MKMapItem(placemark: MKPlacemark(coordinate: CLLocationCoordina

我想绘制从当前用户位置到注释点的多段线,但它似乎没有绘制任何内容:

@IBAction func myButtonGo(_ sender: Any) {
    showRouteOnMap()
}

func showRouteOnMap() {
    let request = MKDirectionsRequest()

    request.source = MKMapItem(placemark: MKPlacemark(coordinate: CLLocationCoordinate2D.init(), addressDictionary: nil))
    request.destination = MKMapItem(placemark: MKPlacemark(coordinate: (annotationCoordinatePin?.coordinate)!, addressDictionary: nil))
    request.requestsAlternateRoutes = true
    request.transportType = .automobile

    let directions = MKDirections(request: request)

    directions.calculate { [unowned self] response, error in guard let unwrappedResponse = response else { return }

        if (unwrappedResponse.routes.count > 0) {
            self.mapView.add(unwrappedResponse.routes[0].polyline)
            self.mapView.setVisibleMapRect(unwrappedResponse.routes[0].polyline.boundingMapRect, animated: true)
        }
    }
}

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    let renderer = MKPolylineRenderer(polyline: overlay as! MKPolyline)
    renderer.strokeColor = UIColor.black
    return renderer
}
我尝试在调试模式下运行,但它在以下行的断点处停止:

directions.calculate { [unowned self] response, error in guard let unwrappedResponse = response else { return }

此错误的原因是什么?

如果它在那里停止,请确保那里没有断点:

左边空白处的深蓝色指示器表示有一个断点。如果您有一个断点,只需单击它以禁用它(将其更改为浅蓝色)或将其拖离以删除它

如果这不是问题(即,它确实崩溃了),那么我们需要知道它是什么类型的崩溃,控制台中显示了什么,等等

如果它没有崩溃,但只是没有绘制路线,请确保已指定地图视图的
委托
(在
viewDidLoad
中或在IB的右侧)


尽管如此,还有一些其他的观察结果:

  • 您的起始坐标是
    CLLocationCoordinate2D()
    (即纬度和长度为0,0,即在太平洋)。这不会导致它崩溃,但如果检查
    错误
    对象,其本地化描述将显示:

    方向不可用

    您应该更正
    坐标

  • 您应该警惕使用异步方法的
    unowned self
    ,因为在返回指令时,
    self
    总是可能被释放,并且它会崩溃。使用
    [弱自我]
    更安全

  • 因此:

    let request = MKDirectionsRequest()
    request.source = MKMapItem(placemark: MKPlacemark(coordinate: sourceCoordinate))
    request.destination = MKMapItem(placemark: MKPlacemark(coordinate: destinationCoordinate))
    request.requestsAlternateRoutes = true
    request.transportType = .automobile
    
    let directions = MKDirections(request: request)
    directions.calculate { [weak self] response, error in
        guard let response = response, error == nil, let route = response.routes.first else {
            print(error?.localizedDescription ?? "Unknown error")
            return
        }
    
        self?.mapView.add(route.polyline)
    }