【问题标题】:Draw polyline with mapkit Swift 3使用 mapkit Swift 3 绘制折线
【发布时间】:2017-10-28 10:49:19
【问题描述】:

我想绘制一条从当前用户位置到注释点的折线,但它似乎没有绘制任何东西:

@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 }

这个错误的原因是什么?

【问题讨论】:

    标签: swift xcode mapkit draw polyline


    【解决方案1】:

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

    左边距的深蓝色指示符表示那里有一个断点。如果您有断点,只需单击它以禁用它(将其更改为浅蓝色)或将其拖动以将其删除。

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

    如果它没有崩溃,只是没有绘制路线,请确保您已指定地图视图的 delegate(在 viewDidLoad 或 IB 中)。


    话虽如此,但还有其他一些观察:

    1. 您的起始坐标是CLLocationCoordinate2D()(即0、0的纬度和经度,即在太平洋中)。这不会导致它崩溃,但如果你检查 error 对象,它的本地化描述会说:

      路线不可用

      您应该将coordinate 更正为source

    2. 您应该警惕使用异步方法的unowned self,因为在返回方向时self 总是有可能被释放,并且它会崩溃。使用[weak 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)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-17
      • 1970-01-01
      • 1970-01-01
      • 2017-05-12
      • 1970-01-01
      • 1970-01-01
      • 2018-11-09
      相关资源
      最近更新 更多