swiftuimapkit

How to convert tap gesture to coordinate in a SwiftUI Map view?


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?


Solution

  • iOS 17 now has a MapReader for the SwiftUI map. You wrap the Map like this:

    struct ContentView: View {
        var body: some View {
            MapReader { reader in
                Map()
                .onTapGesture(perform: { screenCoord in
                    let pinLocation = reader.convert(screenCoord, from: .local)
                    print(pinLocation)
                })
            }
        }
    }
    

    and you can extract the lat/long of the touch.