Why SwiftUI Map Annotation is not updating its title immediately with the selected place name?

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
        }
    }
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật