Search code examples
swiftmapboxpolylinemapbox-marker

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


I tried following code but it draw straight line and i want dashed lines

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

Solution

  • One option is to use an MGLLineStyleLayer, which has a lineDashPattern property.

    This example shows how to add a dashed line, but for your use case, it would look more like:

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

    Then update the shape property on source as necessary.