Showing annotation items in a MapView in SwiftUI

56 Views Asked by At

I have a map view in SwiftUI showing some annotations items. Here is an example.

import SwiftUI
import MapKit

struct MapItem: Identifiable {
    var id = UUID()
    var location: CLLocationCoordinate2D
}

struct ContentView: View {
    @State var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 32.779167, longitude: -96.808891), span: MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1))
    var items = [MapItem(location: CLLocationCoordinate2D(latitude: 32.779167, longitude: -96.808891))]
    var body: some View {
        Map(coordinateRegion: $region, showsUserLocation: true, annotationItems: items) { item in
            MapAnnotation(coordinate: item.location) {
                Rectangle()
                    .frame(width: 10, height: 10)
                    .foregroundColor(.red)
            }
        }
        .ignoresSafeArea()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

The code works as expected, but I get this message in the console every time the map is dragged.

Publishing changes from within view updates is not allowed, this will cause undefined behavior.

Is this a bug in SwiftUI, or is there something wrong with my code?

0

There are 0 best solutions below