Hello and welcome to Swift and the forums!
In your code snippets, the map doesn't actually switch styles because the SwiftUI Map view in iOS 14 doesn't support changing map types out of the box. The id modifier won't magically change the underlying style — it only forces a re-render if the ID is truly different.
The mapStyle(_:) modifier only exists from iOS 17 onwards, so no luck if you need to support iOS 14.
To properly support different map types (standard, satellite, hybrid) on iOS 14, you'll need to drop down to UIKit and use MKMapView via UIViewRepresentable.
Here's a stripped-down example to get you started:
struct MapView: UIViewRepresentable {
@Binding var coordinateRegion: MKCoordinateRegion
let style: MKMapType
func makeUIView(context: Context) -> MKMapView {
let map = MKMapView()
map.showsUserLocation = true
map.delegate = context.coordinator
return map
}
func updateUIView(_ map: MKMapView, context: Context) {
map.region = coordinateRegion
map.mapType = style
}
func makeCoordinator() -> Coordinator {
Coordinator(parent: self)
}
class Coordinator: NSObject, MKMapViewDelegate {
private let parent: MapView
init(parent: MapView) {
self.parent = parent
}
func mapViewDidChangeVisibleRegion(_ mapView: MKMapView) {
parent.coordinateRegion = mapView.region
}
}
}
Then in your SwiftUI view:
if case .openStreetMap = selectedMapStyle {
openStreetMapView()
} else {
MapView(coordinateRegion: $locationManager.region, style: selectedMapStyle)
}
Hope this helps. If you have any questions or extra context about your current code, just shout.
Topic:
UI Frameworks
SubTopic:
SwiftUI
Tags: