Search code examples
swiftuimapkit

How to draw dashed MapPolyline


I've tried and failed to figure out how to format a MapPolyLine with dashes, playing with .stroke and .strokeStyle but I'm stumped. Here's a minimal example. How do I add a format for dashes? Thanks!

import SwiftUI
import MapKit

struct ContentView: View {
    let routes = Routes()

    var body: some View {
        VStack {
            Map() {
                ForEach(routes, id: \.id) { route in
                    MapPolyline(coordinates: route.segment,
                                contourStyle: MapPolyline.ContourStyle.straight)
                    .stroke(route.tint, lineWidth: route.lineWidth)//, dash: route.dash)

                }
            }
        }
    }
}

struct Route: Identifiable {
    let id: String = UUID().uuidString
    var segment: [CLLocationCoordinate2D]
    var tint: Color
    var lineWidth: CGFloat
    var dash: [CGFloat]
}

func Routes() -> [Route] {
        
    var segments: [Route] = []
    
    let routeOne: Route = Route(segment: [
        CLLocationCoordinate2D(latitude: 48.10589, longitude: -122.77899),
        CLLocationCoordinate2D(latitude: 48.0995, longitude: -122.81254),
        CLLocationCoordinate2D(latitude: 48.09196, longitude: -122.81565),
        CLLocationCoordinate2D(latitude: 48.0873599, longitude: -122.84327),
        CLLocationCoordinate2D(latitude: 48.052428, longitude: -122.829886)],
                                tint: Color(.green), lineWidth: 8, dash: [] )
    segments.append(routeOne)
    
    let routeTwo = Route(segment: [
        CLLocationCoordinate2D(latitude: 48.02569, longitude: -123.01255),
        CLLocationCoordinate2D(latitude: 48.040381, longitude: -123.02743),
        CLLocationCoordinate2D(latitude: 48.05617, longitude: -123.04887),
        CLLocationCoordinate2D(latitude: 48.07843, longitude: -123.08072)],
        tint: Color(.red), lineWidth: 8, dash: [8,8] )
    segments.append(routeTwo)
    
    return segments
}

I have tried using .stroke modifier without success.


Solution

  • try something like this, works for me:

    .stroke(route.tint, style: StrokeStyle(lineWidth: route.lineWidth, dash: route.dash))