TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

[Solved] iOS 17 MapKit: How to use Map(selection:)?

Forums > SwiftUI

I followed along WWDC 2023's Meet MapKit for SwiftUI, but am stumped at how to to use Marker selection for my own data.

Creating a selectedItem: MKMapItem? and assigning that to the map does result in the marker indicating it's selected when tapped. But nothing else happens- my private var selectedPlace computed variable never recomputes. Also if I add a if selectedItem { Text("selected") } block in the body, it never succeeds- always showing that the selectedItem is nil. If I change the type of the selectedItem to a MapFeature, nothing happens when it's tapped.

What do I need to do to get Map to update this variable on selection?

Thanks for any help!

Here's my code:

struct Place: Identifiable {
    let id: String
    let name: String
    let coordinate: CLLocationCoordinate2D
}

struct MapView: View {
    var places: [Place]
    @State private var position: MapCameraPosition = .automatic
    @State private var selectedItem: MKMapItem?

    private var selectedPlace: Place? {
        if let selectedItem {
            return places.first(where: { $0.id.hashValue == selectedItem.hashValue })
        }
        return nil
    }

    var body: some View {
        Map(position: $position, selection: $selectedItem) {
            ForEach(places, id: \.id) { place in
                Marker(
                  place.name,
                  monogram: place.icon,
                  coordinate: place.coordinate
                ).tag(place.id)
            }
        }
        .safeAreaInset(edge: .bottom) {
            if let selectedPlace {
                PlaceInfoView(place: selectedPlace)
                    .frame(height: 128)
                    .clipShape(RoundedRectangle(cornerRadius: 10))
                    .padding([.top, .horizontal])
            }
        }
    }
}

2      

Ooof, finally figured this out. So the selection: since I'm using .tag(\.id), is simply my Place's ID (which is a string. Changing selectedItem: String? fixed it.

3      

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

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.