I want to use SwiftUI to display a map and handle touch on the map. Here is my code so far. I have a problem integrating GestureRecognizer in Coordinator specifically accessing self.mapView inside it.
Also adding addGestureRecognizer. How to do that?
=======================================
//
// ContentView.swift
import SwiftUI
import Gomobiletidb
struct ContentView: View {
var body: some View {
VStack {
MapView()
.edgesIgnoringSafeArea(.vertical)
Text("Turtle Rock")
.font(.title)
.padding(.leading, 15)
.padding(.top, 5)
.textFieldStyle(RoundedBorderTextFieldStyle())
VStack {
HStack {
Text("Joshua Tree National Park")
.font(.subheadline)
Spacer()
Text("California")
.font(.subheadline)
}
.padding()
}
}
}
=======================================
//
// MapView.swift
import SwiftUI
import MapKit
struct MapView: UIViewRepresentable {
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
final class Coordinator: NSObject, MKMapViewDelegate {
var control: MapView
init(_ control: MapView) {
self.control = control
longPressGestureRecognizer = UILongPressGestureRecognizer(target: self.control, action: #selector(Coordinator.mapViewLongTapRecognizer(gestureRecognizer:)))
control.addGestureRecognizer(longPressGestureRecognizer)
}
@objc func mapViewLongTapRecognizer( gestureRecognizer: UILongPressGestureRecognizer) {
if (gestureRecognizer == longPressGestureRecognizer){
if (gestureRecognizer.numberOfTouchesRequired == 1){
if gestureRecognizer.state == UIGestureRecognizer.State.began {
let touchPoint: CGPoint = gestureRecognizer.location(in: self.mapView)
}
}
}
}
// MARK: - MKMapViewDelegate
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKOverlayPathRenderer()
return renderer
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
return annotation as? MKAnnotationView
}
}
func makeUIView(context: Context) -> MKMapView {
let mapView = MKMapView(frame: .zero)
mapView.delegate = context.coordinator
mapView.mapType = .hybrid
mapView.showsCompass = true
mapView.showsUserLocation = true
mapView.showsBuildings = true
return mapView
}
func updateUIView(_ mapView: MKMapView, context: Context) {
longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(Coordinator.mapViewLongTapRecognizer(gestureRecognizer:)))
mapView.addGestureRecognizer(longPressGestureRecognizer)
let span = MKCoordinateSpan(latitudeDelta: 2.0, longitudeDelta: 2.0)
let region = MKCoordinateRegion(center: currentLocation.coordinate, span: span)
mapView.setRegion(region, animated: true)
}
}
struct MapView_Preview: PreviewProvider {
static var previews: some View {
MapView()
}
}
=======================================