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

时间:2018-07-17 08:31:38

标签: swift mapbox polyline mapbox-marker

我尝试了以下代码,但它绘制了直线,我想用虚线

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

1 个答案:

答案 0 :(得分:4)

一种选择是使用具有MGLLineStyleLayer属性的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)
}

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