iOS : Swift - How to add pinpoint to map on touch and get detailed address of that location?

SRK picture SRK · Dec 23, 2015 · Viewed 24.3k times · Source

I want to add annotation on touch of iOS map and fetch the detailed address (Placemark) of respective location. How I can achieve this in Swift?

Thanks in advance.

Answer

Moriya picture Moriya · Dec 23, 2015

To react to the touch on map you need to set up a tap recogniser for the mapView

in viewDidLoad:

let gestureRecognizer = UITapGestureRecognizer(target: self, action:"handleTap:")
    gestureRecognizer.delegate = self
    mapView.addGestureRecognizer(gestureRecognizer)

Handle the tap and get the tapped location coordinates:

func handleTap(gestureRecognizer: UILongPressGestureRecognizer) {
    
    let location = gestureRecognizer.location(in: mapView)
    let coordinate = mapView.convert(location, toCoordinateFrom: mapView)
    
    // Add annotation:
    let annotation = MKPointAnnotation()
    annotation.coordinate = coordinate
    mapView.addAnnotation(annotation)
}

Now you only have to implement the MKMapView delegate functions to draw the annotations. A simple google search should get you the rest of that.