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.
This takes three steps: Create some sort of state that will track the coordinates being shown by the map, using MKCoordinateRegion to track the center and zoom level of the map. Prepare an array of locations to use for your annotations. Decide how you want them to be shown on your map.
Overview. A map view displays a region. Use this native SwiftUI view to optionally configure user-allowed interactions, display the user's location, and track a location.
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:#selector(handleTap)) gestureRecognizer.delegate = self mapView.addGestureRecognizer(gestureRecognizer)
Handle the tap and get the tapped location coordinates:
func handleTap(gestureRecognizer: UITapGestureRecognizer) { 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With