'Show a polyline made of Track-Coordinates by Pressing a Button in Map View | SwiftUI

I want to show different tracks by pressing different buttons. I started off with trying to show the polyline for the first track by pressing a button. If I put the "construction" of the polyline in the makeUIView function of my UI Wrapper, I can see it in the map.

However I only want to show it after pressing a button. So I put the polyline-related code in the updateUIView-function and designed the button with the help of an Observable Object class. Unfortunately it doesn't work.

Here's what I got so far (The lat1 and long1 Array are actually much longer):

import SwiftUI
import MapKit
import CoreLocation



//    MARK: ObservableObject
class MapViewModel: ObservableObject {
    @Published var didPressTrack01 = false
}


struct MapView: UIViewRepresentable {
 
    
    //    MARK: UIViewRepresentable
    
    @ObservedObject var viewModel: MapViewModel  
    @Binding var region: MKCoordinateRegion


    let track01_lat = "49.0228176937071,49.022820134536,49.0228225788423"
    
    let track01_long = "8.43144629937264,8.43144455316597,8.43144281824249"
   

    var lat1 : [Double] {
    return track01_lat.components(separatedBy: ",").compactMap(CLLocationDegrees.init)
}

    var lon1 : [Double] {
    return track01_long.components(separatedBy: ",").compactMap(CLLocationDegrees.init)
}
    var trackCoordinates1 : [CLLocationCoordinate2D] {
    
    var LocationsArray = [CLLocationCoordinate2D]()
    for i in 0..<lat1.count {
        LocationsArray.append(CLLocationCoordinate2D(latitude: lat1[i], longitude: lon1[i]))
       }
    return LocationsArray
    }
    

    let map = MKMapView()
    
    ///Creating map view at startup
    func makeUIView(context: Context) -> MKMapView {
        let map = context.coordinator.mapView
        map.setRegion(region, animated: false)
        map.showsUserLocation = true
        
        map.delegate = context.coordinator
        
        return map
    }
    
        
    func updateUIView(_ view: MKMapView, context: Context) {
       
        if viewModel.didPressTrack01 == true {

            let polyline = MKPolyline(coordinates: trackCoordinates1, count: trackCoordinates1.count)
            map.addOverlay(polyline)   
        }       
    }
    
    ///Use class Coordinator method
    func makeCoordinator() -> Coordinator {
        return Coordinator(self)
    }

//MARK: - Core Location manager delegate
class Coordinator: NSObject, MKMapViewDelegate, CLLocationManagerDelegate {
    
    var parent: MapView
    
    init(_  parent: MapView) {
        self.parent = parent
    }

    var mapView = MKMapView()


    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        if let routePolyline = overlay as? MKPolyline {
            let renderer = MKPolylineRenderer(polyline: routePolyline)
            renderer.strokeColor = UIColor.systemRed
            renderer.lineWidth = 2
            return renderer
        }
        return MKOverlayRenderer()
    }
}
        

// MARK: View that shows map to users
struct Tap_Map_View: View {


    @State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude:20.02281, longitude: 8.43188), latitudinalMeters: 180, longitudinalMeters: 180)
    @StateObject var viewModel = MapViewModel()
    
 
    var body: some View {

        ZStack(alignment: .bottom){
            MapView(viewModel: viewModel, region: $region)
                
                Button {
          
                    viewModel.didPressTrack01.toggle()
                    
                    
                } label: {
                    Label("", systemImage: "point.topleft.down.curvedto.point.bottomright.up")
                        
                    }               
            }
      }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source