Search code examples
swiftswiftuimapkitgradientpolyline

SwiftUI Gradient Polyline on Map View


According to this WWDC video gradient Polylines should be available in SwiftUI map views.

https://developer.apple.com/videos/play/wwdc2023/10043/?time=1360

let coordinates = [
        CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194),
        CLLocationCoordinate2D(latitude: 37.3352, longitude: -122.0322),
        CLLocationCoordinate2D(latitude: 34.0522, longitude: -118.2437)
    ]

    let gradient = LinearGradient(colors: [.red, .green, .blue], startPoint: .leading, endPoint: .trailing)

    let stroke = StrokeStyle(lineWidth: 5, lineCap: .round, lineJoin: .round, dash: [10, 10])

    var body: some View {
        Map {
            MapPolyline(coordinates: coordinates)
                .stroke(gradient, style: stroke)
            
        }
    }

Seems to render the whole polyline with the first colour in the given colours for the gradient. Is this a bug/is there another way to achieve this?


Solution

  • You were so close! It works if you stroke the polyline using a simple Gradient, instead of a LinearGradient.

    A Gradient can be created using an array of colors or color stops:

    let gradient = Gradient(colors: [.red, .green, .blue])
    
    // all other code unchanged
    

    Screenshot