UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Maps not updating in MacOS (and iOS)

Forums > SwiftUI

I have a sample project where you select a location from the sidebar and the location will be displayed on the map. You can select any location and the map will update. But as soon as you move the map and then select a different location, the map will not update to the currect location.

struct MapLocation: Identifiable, Hashable {
    let id = UUID()
    let name: String
    let latitude, longitude: Double

    var coordinate: CLLocationCoordinate2D {
        CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
    }
}

struct ContentView: View {
    let mapLocation: [MapLocation] = [
        MapLocation(name: "Denver", latitude: 39.83205, longitude: -105.01680),
        MapLocation(name: "Key West", latitude: 24.55674, longitude: -81.78736),
        MapLocation(name: "Dallas", latitude: 32.93933, longitude: -96.67838),
    ]

    let defaultLocation = MapLocation(name: "Nashville", latitude: 36.28260, longitude: -86.65211)

    @State private var selectedLocation: MapLocation?

    var body: some View {
        NavigationSplitView {
            List(selection: $selectedLocation) {
                ForEach(mapLocation) { location in
                    NavigationLink(value: location) {
                        Text(location.name)
                            .font(.largeTitle)
                    }
                }
            }
        } detail: {
            MapDetailView(location: selectedLocation ?? defaultLocation)
        }
    }
}

#Preview {
    ContentView()
}

struct MapDetailView: View {
    var location: MapLocation
    @State private var position: MapCameraPosition = .automatic
    var body: some View {
        VStack {
            Map(position: $position) {
                Marker(location.name, coordinate: location.coordinate)
            }
                .frame(height: 500)
            Text("Selected locaton: \(location.name)")
        }
    }
}

Any thoughts as to why this is happening, or did I miss something somewhere. Thanks

3      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.