Mapkit and swiftui

I have updated my map code so that now I have a region that is set as a state var in my strict. My map links to this state var.

the problem is now I want to update my map based on my long and last variables that are passed to the struct is there a way to do this - going crazy trying to do this


In order to programmatically change the region the Map shows, you can use a @Published property in your app's model, binding the Map's coordinateRegion (or mapRect, depending on your needs) to that value. This will allow you to change your model's property in response to external factors (say, loading new data from the network or from disk) and have the Map automatically update to show the new region.

For example:

Code Block
class ViewModel: ObservableObject {
@Published var coordinateRegion: MKCoordinateRegion = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 37.334900, longitude: -122.009020), latitudinalMeters: 1000, longitudinalMeters: 1000)
}
class MyModelController {
public let viewModel: ViewModel = ViewModel();
public func updateData() {
someAsynchronousTask(completion: { _ in
self.viewModel.coordinateRegion = MKCoordinateRegion(...)
});
}
}
struct MyView: View {
@ObservedObject var model: ViewModel
init(_ viewModel: ViewModel) {
self.viewModel = viewModel
}
var body: some View {
Map(coordinateRegion: $viewModel.coordinateRegion)
}
}

But binding a published property to Maps and changing it anywhere in the code gives this bloody [SwiftUI] Publishing changes from within view updates is not allowed, this will cause undefined behavior. warning on iOS 16, XCode 14...

In iOS 17 Map(coordinateRegion:) is deprecated. What is the idiomatic way to get a binding to the (possibly user-positioned) current map region?

Mapkit and swiftui
 
 
Q