The issue I’m encountering with the ‘identifiableMapItem.mapItem.name’ displaying “Unknown Location” initially and then updating only after another annotation is added.
It seems to be related to the asynchronous process of the ‘getPlaceAddressFrom’ method in the MapViewModel.
When I tap to add an annotation, the ‘getPlaceAddressFrom’ method is called asynchronously to fetch the address. However, since this call is asynchronous, the Annotation view is initially rendered with the placeholder “Unknown Location” because the actual name has not been retrieved yet. Once the address is fetched and the state is updated, the view should automatically update with the new name. But it seems like the view is not refreshing immediately to reflect the new name.
Here is the steps to reproduce;
1-) You tap to add an annotation, which triggers the asynchronous address fetch.
2-) The Annotation view is rendered with “Unknown Location” because the address hasn’t been retrieved yet.
3-) When you add a second annotation, it triggers a state change that causes the view to re-render.
4-) During this re-render, the first annotation now has the address available and updates accordingly, but the second one is now in the initial state of waiting for its address.
Here is the minimal reproducible example:
struct MapView: View {
@ObservedObject var viewModel = MapViewModel()
@State private var routes: [MKRoute] = []
@State private var position = MapCameraPosition.region(
MKCoordinateRegion(
center:CLLocationCoordinate2D(latitude: 51.501330, longitude: -0.141889),
span: MKCoordinateSpan(latitudeDelta: 10, longitudeDelta: 10)
)
)
@State private var isShownMenu: Bool = false
@State private var isBool = false
var body: some View {
ZStack {
MapReader { proxy in
Map(
position: $position
) {
ForEach(viewModel.selectedMapItems, id: .id) { identifiableMapItem in
Annotation(
identifiableMapItem.mapItem.name ?? "Unknown",
coordinate: identifiableMapItem.mapItem.placemark.coordinate,
content: {
ZStack {
Circle()
.foregroundStyle(.indigo.opacity(0.5))
.frame(width: 50, height: 50)
if let systemName = viewModel.selectedImageSystemNames[identifiableMapItem.id.uuidString] {
Image(systemName: systemName)
.symbolEffect(.variableColor)
.padding()
.foregroundStyle(.white)
.background(viewModel.randomColor())
.clipShape(Circle())
} else {
Image(systemName: "car.front.waves.up")
.symbolEffect(.variableColor)
.padding()
.foregroundStyle(.white)
.background(viewModel.randomColor())
.clipShape(Circle())
}
}
}
)
}
ForEach(viewModel.polylines, id: .self) { polyline in
MapPolyline(polyline)
}
}
.disabled(viewModel.selectedMenuItem == nil ? true : false)
.safeAreaInset(edge: .trailing) {
VStack(spacing: 18) {
Button {
viewModel.undoLastMarkerAndPolyline()
} label: {
Image(systemName: "arrow.counterclockwise.circle.fill")
.resizable()
.frame(width: 48, height: 48)
}
.disabled(viewModel.selectedMapItems.count == 0)
Button {
viewModel.animate.toggle()
} label: {
Image(systemName: "play.fill")
.resizable()
.frame(width: 48, height: 48)
}
.disabled(viewModel.points.count == 0)
Button(action: {
isShownMenu = true
},
label: {
Menu {
Button(action: {
viewModel.selectedMenuItem = "figure.walk.motion"
},
label: {
HStack {
Text("Walk")
Image(systemName: "figure.walk.motion")
}
})
Button(action: {
viewModel.selectedMenuItem = "ferry.fill"
},
label: {
HStack {
Text("Ferry")
Image(systemName: "ferry.fill")
}
})
} label: {
Image(systemName: "car.ferry.fill")
.resizable()
.frame(width: 48, height: 48)
}
})
}
.padding(.trailing, 8)
}
.onAppear {
viewModel.createPolylines()
}
.onChange(of: viewModel.selectedMapItems) { _, _ in
viewModel.createPolylines()
}
.onTapGesture { position in
guard let coordinate = proxy.convert(position, from: .local),
let selectedMenuItem = viewModel.selectedMenuItem else {
return
}
let newMapItem = MKMapItem(
placemark: MKPlacemark(
coordinate: CLLocationCoordinate2D(
latitude: coordinate.latitude,
longitude: coordinate.longitude
)
)
)
let newIdentifiableMapItem = IdentifiableMapItem(mapItem: newMapItem)
viewModel.selectedMapItems.append(newIdentifiableMapItem)
viewModel.selectedImageSystemNames[newIdentifiableMapItem.id.uuidString] = selectedMenuItem
Task {
try? await viewModel.getPlaceAddressFrom(identifiableMapItem: newIdentifiableMapItem)
}
}
}
}
.onChange(of: viewModel.selectedMenuItem) { _, _ in
viewModel.createAnnotations()
}
}
}
struct IdentifiableMapItem: Equatable {
let id = UUID()
var mapItem: MKMapItem
}
@MainActor
class MapViewModel: ObservableObject {
@Published var points: [CLLocationCoordinate2D] = []
@Published var polylines: [MKPolyline] = []
@Published var selectedMenuItem: String?
@Published var systemName: String?
@Published var selectedMapItems: [IdentifiableMapItem] = []
@Published var selectedImageSystemNames: [String: String] = [:]
@Published var animate: Bool = false
func createAnnotations() {
guard let selectedMenuItem = selectedMenuItem else { return }
for identifiableMapItem in selectedMapItems {
if selectedImageSystemNames[identifiableMapItem.id.uuidString] == nil {
selectedImageSystemNames[identifiableMapItem.id.uuidString] = selectedMenuItem
}
}
}
func createPolylines() {
polylines.removeAll()
var points: [CLLocationCoordinate2D] = []
for identifiableMapItem in selectedMapItems {
points.append(identifiableMapItem.mapItem.placemark.coordinate)
}
self.points = points
let polyline = MKPolyline(coordinates: points, count: points.count)
polylines.append(polyline)
}
func undoLastMarkerAndPolyline() {
if !selectedMapItems.isEmpty {
selectedMapItems.removeLast()
if let idToRemove = selectedMapItems.last?.id.uuidString {
selectedImageSystemNames.removeValue(forKey: idToRemove)
}
animate.toggle()
createPolylines()
}
}
func getPlaceAddressFrom(identifiableMapItem: IdentifiableMapItem) async throws -> String {
let geocoder = CLGeocoder()
let location = CLLocation(
latitude: identifiableMapItem.mapItem.placemark.coordinate.latitude,
longitude: identifiableMapItem.mapItem.placemark.coordinate.longitude
)
do {
let places = try await geocoder.reverseGeocodeLocation(location)
guard let place = places.first,
let city = place.administrativeArea,
let locality = place.locality
else {
throw CLError(.geocodeFoundNoResult)
}
let address = city + " " + locality
return address
} catch {
throw error
}
}
}