如何使用 mapbox 绘制带虚线的折线 (MGLPolyline):swift

How to draw polyline(MGLPolyline) with dashed lines using mapbox : swift

我试过下面的代码,但它画的是直线,我想要虚线

@IBOutlet var navigationView: MGLMapView!
var polyline: MGLPolyline!

 override func viewDidLoad() {
        super.viewDidLoad()

        var mapCoordinates: [CLLocationCoordinate2D] = []
        let newCoord1 = CLLocationCoordinate2D(latitude: 8.5241, longitude: 76.9366)
        let newCoord2 = CLLocationCoordinate2D(latitude:11.8745, longitude: 75.3704)

        mapCoordinates.append(newCoord1)
        mapCoordinates.append(newCoord2)

        polyline = MGLPolyline(coordinates: mapCoordinates, count: UInt(mapCoordinates.count))

        navigationView.add(polyline)
}

一种选择是使用 MGLLineStyleLayer, which has a lineDashPattern 属性。

This example 显示如何添加虚线,但对于您的用例,它看起来更像:

func mapView(_ mapView: MGLMapView, didFinishLoading style: MGLStyle) {
            var mapCoordinates: [CLLocationCoordinate2D] = []
    let newCoord1 = CLLocationCoordinate2D(latitude: 8.5241, longitude: 76.9366)
    let newCoord2 = CLLocationCoordinate2D(latitude:11.8745, longitude: 75.3704)

    mapCoordinates.append(newCoord1)
    mapCoordinates.append(newCoord2)

    polyline = MGLPolyline(coordinates: mapCoordinates, count: UInt(mapCoordinates.count))

    source = MGLShapeSource(identifier: "line", shape: polyline, options: nil)
    style.addSource(source)

    let layer = MGLLineStyleLayer(identifier: "line-layer", source: source)
    layer.lineDashPattern = NSExpression(forConstantValue: [2, 1.5])
    style.addLayer(layer)
}

然后根据需要在 source 上更新 shape 属性。