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) |
} |
} |