Hi. This is my MapView code
import SwiftUI
import MapKit
struct MapView: UIViewRepresentable {
var region: MKCoordinateRegion
var polylineCoordinates: [CLLocationCoordinate2D]?
func makeUIView(context: Context) -> MKMapView {
let mapView = MKMapView()
mapView.delegate = context.coordinator
mapView.region = region
if let polylines = polylineCoordinates {
let polyline = MKPolyline(coordinates: polylines, count: polylines.count)
mapView.addOverlay(polyline)
}
return mapView
}
func updateUIView(_ view: MKMapView, context: Context) {
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
}
class Coordinator: NSObject, MKMapViewDelegate {
var parent: MapView
init(_ parent: MapView) {
self.parent = parent
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if overlay is MKPolyline {
let routePolyline = overlay as! MKPolyline
let renderer = MKPolylineRenderer(polyline: routePolyline)
renderer.strokeColor = UIColor.white
renderer.lineWidth = 2
return renderer
}
return MKOverlayRenderer()
}
}
If i do this
var body: some View {
MapView(region: [array of CLLocationCoordinage2D])
.edgesIgnoringSafeArea(.all)
}
it works since the value of the region property is set in the constructor. However, what i want is to set the region property in the onAppear closure. What is lacking here since it does not work.
I wish to do something like this
var body: some View {
MapView(region: region)
.edgesIgnoringSafeArea(.all)
.onAppear {
region = [array of CLLocationCoordinage2D]
}
}
I want to apply the same thing to polylineCoordinates property but for now, if I can make it work with region, I am sure the same thing can be applied to polylineCoordinates property.
Thoughts?