Post

Replies

Boosts

Views

Activity

Reply to MapSelection of MapFeatures and MKMapItems
I'm the original post author, replying from my work account. Here is an example that allows for selection of MapFeatures and MKMapItems. It shows Apple Stores nearby and allows those search results (MKMapItems) to be selected, as well as the MapFeatures to be selected. The key thing that I was missing before was the the need for the .tag modifier on the Marker. This example shows how to achieve selection of MapFeatures and MKMapItems. import SwiftUI import MapKit struct ContentView: View { @State var position: MapCameraPosition = .automatic @State var selection: MapSelection<MKMapItem>? @State private var items: [MKMapItem] = [] var body: some View { VStack { Map(position: $position, selection: $selection) { ForEach(items, id: \.self) { item in Marker(item: item) .tag(MapSelection(item)) } } }.onAppear { Task { try? await search(for: "Apple Store") } } } func search(for query: String) async throws { let request = MKLocalSearch.Request() request.naturalLanguageQuery = query request.resultTypes = [.pointOfInterest, .address] Task { let search = MKLocalSearch(request: request) let response = try? await search.start() items = response?.mapItems ?? [] } } }
5d