Adding a pin annotation to a map view on a long press in swift

1) Instantiate a UILongPressGestureRecognizer and add it to the MKMapView.

2) When the selector gets called after the user has a long press, call the addAnnotation method in MKMapView with the appropriate title and coordinate.

3) Then make sure you conform to the MKMapViewDelegate and implement viewForAnnotation: which will be called right after you add the annotation and return a MKPinAnnotationView


  1. add UILongPressGestureRecognizer to your MapView

    var uilgr = UILongPressGestureRecognizer(target: self, action: "addAnnotation:")
    uilgr.minimumPressDuration = 2.0
    
    map.add (uilgr)
    
    //IOS 9
    map.addGestureRecognizer(uilgr) 
    
  2. Add annotation on Long press detect - func:

    func addAnnotation(gestureRecognizer:UIGestureRecognizer){
        if gestureRecognizer.state == UIGestureRecognizerState.Began {
            var touchPoint = gestureRecognizer.locationInView(map)
            var newCoordinates = map.convertPoint(touchPoint, toCoordinateFromView: map)
            let annotation = MKPointAnnotation()
            annotation.coordinate = newCoordinates
    
            CLGeocoder().reverseGeocodeLocation(CLLocation(latitude: newCoordinates.latitude, longitude: newCoordinates.longitude), completionHandler: {(placemarks, error) -> Void in
                if error != nil {
                    println("Reverse geocoder failed with error" + error.localizedDescription)
                    return
                }
    
            if placemarks.count > 0 {
                let pm = placemarks[0] as! CLPlacemark
    
                // not all places have thoroughfare & subThoroughfare so validate those values
                annotation.title = pm.thoroughfare + ", " + pm.subThoroughfare
                annotation.subtitle = pm.subLocality
                self.map.addAnnotation(annotation)
                println(pm)
            }
            else {
                annotation.title = "Unknown Place"
                self.map.addAnnotation(annotation)
                println("Problem with the data received from geocoder")
            }
            places.append(["name":annotation.title,"latitude":"\(newCoordinates.latitude)","longitude":"\(newCoordinates.longitude)"])
        })
    }
    }
    
  3. or you can add annotation without any title:

    func action(gestureRecognizer:UIGestureRecognizer){
        var touchPoint = gestureRecognizer.locationInView(map)
        var newCoordinates = map.convertPoint(touchPoint, toCoordinateFromView: map)
        let annotation = MKPointAnnotation()
        annotation.coordinate = newCoordinates
        map.addAnnotation(annotation)
    }