Recommend the approach described in this blog post which also works for SwiftData. https://www.avanderlee.com/swift/valuetransformer-core-data/
Post
Replies
Boosts
Views
Activity
It would be great to be able to get a MapFeature from an MKMapItem so that we can access the image and color associated with the MapFeature. Those are not available on the MKMapItem presently.
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 ?? []
}
}
}