Best way to move the region of a SwiftUI Map

I'm trying to have the region of a SwiftUI Map show a specific train. The compiler complains that the train property (see sample code below) is not available when the region property is being initialized. My solution to this is to set the location to the centre of the city, then set it to the train's location when the view appears.

Code Block swift
struct MapView: View {
    @Binding var train: Train
    @State var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: CLLocationDegrees(/* coordinate presented as a Double literal */), longitude: CLLocationDegrees(/* coordinate presented as a Double literal */)), latitudinalMeters: CLLocationDistance(1000), longitudinalMeters: CLLocationDistance(1000))
    
    var body: some View {
        Map(coordinateRegion: $region, interactionModes: .zoom, annotationItems: [train], annotationContent: { (train) in
            return MapMarker.init(coordinate: CLLocationCoordinate2D(latitude: CLLocationDegrees(train.position!.latitude), longitude: CLLocationDegrees(train.position!.longitude)))
        })
        .edgesIgnoringSafeArea(.bottom)
        .navigationBarTitle("Train #\(train.runNumber)")
        .onAppear {
            region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: CLLocationDegrees(train.position!.latitude), longitude: CLLocationDegrees(train.position!.longitude)), span: MKCoordinateSpan(latitudeDelta: CLLocationDegrees(1000), longitudeDelta: CLLocationDegrees(1000)))
        }
    }
}


Answered by Frameworks Engineer in 616048022
Hi thafner,

Apologies, linked the wrong post before. The correct link for the post that gives example code for how to programmatically change the region of the Map can be found here.
Hello thafner,

Guidance for programmatically changing the region of the Map was given in a previous post and can be seen here

Let us know if you have any further question!
Accepted Answer
Hi thafner,

Apologies, linked the wrong post before. The correct link for the post that gives example code for how to programmatically change the region of the Map can be found here.
Best way to move the region of a SwiftUI Map
 
 
Q