- Маркер создан где пользователь нажал
- Местоположение пользователя отображается с помощью синей точки.
Map()
.onTapGesture { tapLocation in
print(tapLocation)
}
.mapControls {
MapUserLocationButton()
}
В настоящее время у меня есть неприятный код для использования MKMapView с прикрепленным к нему UITapGestureRecouncer. Пользователь может коснуться точки, и он получит местоположение касания, преобразованное в координаты из MKMapView и установленное как MKPointAnnotation(). Местоположение пользователя также устанавливается как переменная состояния, поэтому это приводит к постоянной перерисовке контакта местоположения пользователя (неприятно).
import SwiftUI
import MapKit
struct MapInput: UIViewRepresentable {
@Binding var tappedCoordinate: CLLocationCoordinate2D?
@Binding var userLocation: CLLocation?
func makeUIView(context: Context) -> MKMapView {
let mapView = MKMapView()
// Add Tap Gesture Recognizer
let tapGestureRecognizer = UITapGestureRecognizer(
target: context.coordinator,
action: #selector(Coordinator.handleTap(gesture:))
)
mapView.addGestureRecognizer(tapGestureRecognizer)
return mapView
}
func updateUIView(_ uiView: MKMapView, context: Context) {
// Remove existing annotations
uiView.removeAnnotations(uiView.annotations)
// Add new annotation if there's a tapped coordinate
if let coordinate = tappedCoordinate {
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
annotation.title = "POI"
uiView.addAnnotation(annotation)
}
if let user = userLocation {
let annotation = MKPointAnnotation()
annotation.coordinate = user.coordinate
annotation.title = "USER"
uiView.addAnnotation(annotation)
}
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject {
var parent: MapInput
init(_ parent: MapInput) {
self.parent = parent
}
@objc func handleTap(gesture: UITapGestureRecognizer) {
let mapView = gesture.view as! MKMapView
let touchPoint = gesture.location(in: mapView)
let coordinate = mapView.convert(touchPoint, toCoordinateFrom: mapView)
parent.tappedCoordinate = coordinate
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/793 ... mark-point
Мобильная версия