9

I'm trying to add a MapAnnotation item to my Map() View from MapKit.

Everything works fine if you add coordinates manually in a TextField, but I can't find any way to add it by tapping on the map.

I've read a lot on the internet but I've found nothing about onTap() map event handling.

This is what my map view looks like so far:

struct MyMap : View {
    
    @State private var myRegion:MKCoordinateRegion = {
        var newRegion = MKCoordinateRegion()
        newRegion.center.latitude = 53.7576508
        newRegion.center.longitude = -11.1811597
        newRegion.span.latitudeDelta = 0.1
        newRegion.span.longitudeDelta = 0.1
        
        return newRegion
    }()
    
    
    @State private var annotationItems : [Annotation] = [
        Annotation(name: "Pin1", description: "myDescription", coordinate: CLLocationCoordinate2D(latitude: 123.7576508, longitude: -7.2373215))
    ]
    
    var body: some View {
        
        ZStack {
            Map(coordinateRegion: self.$myRegion, interactionModes: .all, annotationItems: annotationItems){ item in
                MapAnnotation(coordinate: item.coordinate){
                    PinView(pin: item)
                }
                
            }
            .edgesIgnoringSafeArea(.all)
        }
    }
}

Is there any way to get the coordinate of where user tapped on the map?

fake girlfriends
  • 10,377
  • 2
  • 38
  • 42
Alessio Raddi
  • 358
  • 1
  • 4
  • 18
  • I deleted my answer because the OP wants the answer to be exclusively in SwiftUI. That said, https://stackoverflow.com/questions/56513942/how-to-detect-a-tap-gesture-location-in-swiftui may help. Furthermore, because UIKit and SwiftUI can work together side by side in the same project, you can take advantage of `convert(touch, toCoordinateFrom: mapView)` in the tap gesture handler in UIKit if it's too much trouble getting it in SwiftUI. – fake girlfriends May 01 '21 at 16:40
  • Possibly same issue as https://stackoverflow.com/questions/63110673/tapping-an-mkmapview-in-swiftui – Vendel Serke Mar 10 '22 at 17:25

0 Answers0