How to add a push pin to a MKMapView(IOS) when touching?

43,487

Thanks to Anna for providing such a great answer! Here is a Swift version if anybody is interested (the answer has been updated to Swift 4.1 syntax).

Creating UILongPressGestureRecognizer:

let longPressRecogniser = UILongPressGestureRecognizer(target: self, action: #selector(MapViewController.handleLongPress(_:)))
longPressRecogniser.minimumPressDuration = 1.0
mapView.addGestureRecognizer(longPressRecogniser)

Handling the gesture:

@objc func handleLongPress(_ gestureRecognizer : UIGestureRecognizer){
    if gestureRecognizer.state != .began { return }

    let touchPoint = gestureRecognizer.location(in: mapView)
    let touchMapCoordinate = mapView.convert(touchPoint, toCoordinateFrom: mapView)

    let album = Album(coordinate: touchMapCoordinate, context: sharedContext)

    mapView.addAnnotation(album)
}
Share:
43,487
Christophe Debove
Author by

Christophe Debove

Updated on May 18, 2020

Comments

  • Christophe Debove
    Christophe Debove about 4 years

    I had to get the coordinate of a point where the user touch on a MKMapView. I'm not working with the Interface Builder. Can you give me one example?