Search code examples
swiftuiswiftui-map

Get coordinates in the onLongPressGesture on the Map


My question is very similar to this one: Capture touchDown location of onLongPressGesture in swiftUI?

However, there's one significant peculiarity: I want to get the coordinates of the .onLongPressGesture on the Map. The solution in the original question has two major issues in this case:

  • It breaks the default Map dragging functionality.

  • It captures the coordinate on "release" - not on "press and hold for X seconds". I want to get coordinates after pressing and holding for the configured amount of seconds (minimumDuration parameter), but before lifting the finger.

I tried different combinations of gestures in different orders: .onTapGesture, DragGesture, etc, but couldn't combine them in a workable way (either dragging of the map gets broken, or the coordinate is detected upon the finger lifting, or some other issues).

Also, I tried to create a transparent overlay and apply some gestures there, but didn't manage either...

I've also seen this question (and answer), but it doesn't help, because it doesn't capture the coordinates (and, IIRC, it also broke the dragging functionality): Anybody got SwiftUI+MapKit+LongPress working?


Solution

  • Update 2024

    Based on Vincente's comment, it is possible to do it now in iOS 18: https://stackoverflow.com/a/78652172/4691224

    Original Answer

    Based on the fact that there are no answers here (and no answers on Apple Developer Forum either) and none of my further experiments succeeded, I assume that it's, unfortunately, not possible to achieve the desired behaviour with the Map component. I had to fall-back to the combination of MKMapView and UILongPressGestureRecognizer. More details can be found in the answers to this question: Adding a pin annotation to a map view on a long press in swift