Post

Replies

Boosts

Views

Activity

Reply to How to use SwiftUI to display a map and handle touch on the map?
After working some time on this problem, I think I came up with a solution in Swift 5 after looking at this stack owerflow article: iOS : Swift - How to add pinpoint to map on touch and get detailed address of that location? - https://stackoverflow.com/questions/34431459/ios-swift-how-to-add-pinpoint-to-map-on-touch-and-get-detailed-address-of-th First, you create a subclass of MKMapView: import Foundation import MapKit final class WrappedMap: MKMapView { 		var onLongPress: (CLLocationCoordinate2D) -> Void = { _ in } 		init() { 				super.init(frame: .zero) 				let gestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleTap(sender:))) 				gestureRecognizer.minimumPressDuration = 0.8 				addGestureRecognizer(gestureRecognizer) 		} 		@objc func handleTap(sender: UILongPressGestureRecognizer) { 				if sender.state == .began { 						let location = sender.location(in: self) 						let coordinate = convert(location, toCoordinateFrom: self) 						onLongPress(coordinate) 				} 		} 		required init?(coder: NSCoder) { 				fatalError("init(coder:) has not been implemented") 		} } Now, you use this view instead of the normal MKMapView but you still have all the functionallity because you have MKMapView as the super class. So you add this to your swiftUI code of the MapView: import SwiftUI import MapKit struct MapView: UIViewRepresentable { 		@State private var annotation = MKPointAnnotation() 		func makeUIView(context: Context) -> MKMapView { 				let mapView = WrappedMap() 				mapView.delegate = context.coordinator 				mapView.onLongPress = addAnnotation(for:) 				return mapView 		} 		func updateUIView(_ uiView: MKMapView, context: Context) { 				uiView.removeAnnotations(uiView.annotations) 				uiView.addAnnotation(annotation) 		} 		func addAnnotation(for coordinate: CLLocationCoordinate2D) { 				let newAnnotation = MKPointAnnotation() 				newAnnotation.coordinate = coordinate 				annotation = newAnnotation 		} } extension MapView { 		class Coordinator: NSObject, MKMapViewDelegate { 				var parent: MapView 				init(_ parent: MapView) { 						self.parent = parent 				} 		} 		func makeCoordinator() -> Coordinator { 				Coordinator(self) 		} } struct MapView_Previews: PreviewProvider { 		static var previews: some View { 				MapView() 				.edgesIgnoringSafeArea(.all) 		} } The Coordinator isn't used in this example, but you might need it when you use this view. I hope this solutions works for your problem altough it has been something like a year since you asked.
Sep ’20