SwiftUI Gradient Polyline on Map View

66 Views Asked by At

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?

2

There are 2 best solutions below

0
Benzy Neez On BEST ANSWER

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

0
J W On

Their is no Api for now, but we can create ourselves, I wrote an example, hopefully can help you.

Solution Path: https://github.com/OAK-WJR/SwiftUI-ProblemSolutions.git

Thoughts: Create a custom UIViewRepresentable to embed MKMapView into the SwiftUI view, and use custom MKOverlay and MKOverlayRenderer to achieve the gradient effect

1: Create a gradient polygon overlay

2: Create a gradient polygon renderer

3: Embed MKMapView in SwiftUI

Results Display: enter image description here