In swiftui, I want to show a map view with a marker to a specific location aligned with the map's center. when I move the map, the marker also needs to move to get the location of the specific point. I tried the below code but the map moves and the marker doesn't. is there any solution
struct MapView: View {
@ObservedObject var appTheme: AppTheme
struct MapMarker: Identifiable {
let id = UUID()
var coordinate: CLLocationCoordinate2D
}
@State private var markerCoordinate = CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194)
@State private var mapCoordinate = CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194)
@GestureState private var translation: CGSize = .zero
var body: some View {
VStack {
Map(coordinateRegion: .constant(MKCoordinateRegion(center: mapCoordinate, span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05))),
showsUserLocation: true,
userTrackingMode: .constant(.follow),
annotationItems: [MapMarker(coordinate: markerCoordinate)],
annotationContent: { item in
MapPin(coordinate: item.coordinate, tint: .red)
})
}
.gesture(DragGesture()
.updating($translation) { value, state, _ in
state = value.translation
}
.onEnded { value in
let offset = value.translation
let translation = CGSize(width: offset.width / 1000, height: -offset.height / 1000)
mapCoordinate = CLLocationCoordinate2D(latitude: mapCoordinate.latitude + translation.height, longitude: mapCoordinate.longitude + translation.width)
markerCoordinate = mapCoordinate
print("New Marker Coordinate: \(markerCoordinate)")
}
)
.onAppear {
print("Initial Marker Coordinate: \(markerCoordinate)")
}
}
}