I need to make it so somebody can faucet on a Map
and do the next:
- A
Marker
is made the place the person tapped - Person location is seen with the native "blue dot"
Many different apps like Uber or DoorDash have this be doable, however I am unable to discover something related on it on-line. Articles advocate this technique, but when I attempt making a Marker
, it says this was deprecated. If I attempt getting tapLocation
the situation just isn’t in world coordinates so its not helpful.
Map()
.onTapGesture { tapLocation in
print(tapLocation)
}
.mapControls {
MapUserLocationButton()
}
At present I’ve some nasty code to make use of a MKMapView
with a UITapGestureRecognizer
connected to it. The person can faucet some extent and it will get the faucet location transformed to the coordinate location from the MKMapView
and set as a MKPointAnnotation()
. The Customers location can also be set as a state variable so this forces redraws of the USER Location pin continuously (nasty).
import SwiftUI
import MapKit
struct MapInput: UIViewRepresentable {
@Binding var tappedCoordinate: CLLocationCoordinate2D?
@Binding var userLocation: CLLocation?
func makeUIView(context: Context) -> MKMapView {
let mapView = MKMapView()
// Add Faucet Gesture Recognizer
let tapGestureRecognizer = UITapGestureRecognizer(
goal: context.coordinator,
motion: #selector(Coordinator.handleTap(gesture:))
)
mapView.addGestureRecognizer(tapGestureRecognizer)
return mapView
}
func updateUIView(_ uiView: MKMapView, context: Context) {
// Take away present annotations
uiView.removeAnnotations(uiView.annotations)
// Add new annotation if there is a tapped coordinate
if let coordinate = tappedCoordinate {
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
annotation.title = "POI"
uiView.addAnnotation(annotation)
}
if let person = userLocation {
let annotation = MKPointAnnotation()
annotation.coordinate = person.coordinate
annotation.title = "USER"
uiView.addAnnotation(annotation)
}
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject {
var guardian: MapInput
init(_ guardian: MapInput) {
self.guardian = guardian
}
@objc func handleTap(gesture: UITapGestureRecognizer) {
let mapView = gesture.view as! MKMapView
let touchPoint = gesture.location(in: mapView)
let coordinate = mapView.convert(touchPoint, toCoordinateFrom: mapView)
guardian.tappedCoordinate = coordinate
}
}
}