In SwiftUI, when creating an annotation on a Map, there's no way to move an existing Annotation after it's been placed on a Map.
Example:
import SwiftUI
import MapKit
struct AnnotationItem: Identifiable {
var id: UUID
var coordinate: CLLocationCoordinate2D
}
struct MapTest: View {
@Binding var annonations: [AnnotationItem]
var body: some View {
Map(
coordinateRegion: $region,
annotationItems: annotations
) { annotation in
MapAnnotation(
coordinate: annotation.coordinate
) {
Circle()
.foregroundColor(.blue)
.frame(width: 12, height: 12)
}
}
}
.frame(width: 500, height: 500)
}
}
extension MapTest {
class ViewModel: ObservableObject {
@Published var annotations: [AnnotationItem] = [
AnnotationItem(
id: UUID(),
coordinate: .init(latitude: 0, longitude: 0)
)
]
// Doesn't move the annotation
func moveTest1() {
annotations.first?.coordinate = .init(latitude: 1, longitude: 1)
}
// Moves the annotation with a flicker
func moveTest2() {
annotations = [
AnnotationItem(
id: UUID(),
coordinate: .init(latitude: 0, longitude: 0)
)
]
}
}
}
In this example, the function move1() doesn't have any affect on the annotation, even though I think it should.
The function move2() moves the annotation, but has a flicker effect because it's creating a new AnnotationItem with a new UUID and replacing the old one.
Is this a bug? Or is there no way to smoothly animate an annotation from one location to another?