Nowadays there are may times when you need to use map in your iOS application. There are lots of things that are implemented using maps. This blog includes the explanation of how you can get location of a place by tapping on any place on map.
![](http://findnerd.s3.amazonaws.com/imagedata/9100/9100.jpg)
Here we are going to use iOS default Apple map for getting lat and long of a place.
Step 1:- Create a new Xcode project and give an appropriate name to the project.
Step 2:- Go to Main.storyboard, you can see there is already an empty View Controller scene, pick Map Kit View and place it on the view controller.
Step 3:- Give proper constraints to the map view so it should be properly visible at run time, here I have given Leading = 10, Trailing = 10, Top = 10 and Bottom = 10 to the outer view.
By now your Main.storyboard will look like this:-
![](http://findnerd.s3.amazonaws.com/imagedata/9094/9094.png)
Step 4:- Create outlet for map view by tapping on the map view, then right click and drag from Main.storyboard to the controller and assign a name like this :-
![](http://findnerd.s3.amazonaws.com/imagedata/9095/9095.png)
Step 5:- Now, moving to the coding part. Go to ViewController.swift.
Right now you must be having an error on the outlet you have just created, just import MapKit. Yes the error is gone.
Step 6:- Modify viewDidLoad() method like this :-
override func viewDidLoad() {
super.viewDidLoad()
// For getting location while tapping on map we need to add UITapGestureRecognizer
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap))
// mapView is the outlet of map
mapView.addGestureRecognizer(tapGesture)
// Do any additional setup after loading the view, typically from a nib.
}
Step 7:- You can see that there is an error where we have given the #selector stating unrecognised selector, it is because we have not yet define that method. So, now define the handleTap method as :-
func handleTap(gestureReconizer: UITapGestureRecognizer) {
let location = gestureReconizer.location(in: mapView)
let coordinate = mapView.convert(location,toCoordinateFrom: mapView)
// Add annotation:
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
print(" Coordinates ======= \(coordinate)")
/* to show only one pin while tapping on map by removing the last.
If you want to show multiple pins you can remove this piece of code */
if mapView.annotations.count == 1 {
mapView.removeAnnotation(mapView.annotations.last!)
}
mapView.addAnnotation(annotation) // add annotaion pin on the map
}
Its done!
Run you project. You can see that map view is there, tap on any place on the map, annotation pin is shown and the result is print in console.
Here are the output windows:-
![](http://findnerd.s3.amazonaws.com/imagedata/9096/9096.png)
![](http://findnerd.s3.amazonaws.com/imagedata/9097/9097.png)
![](http://findnerd.s3.amazonaws.com/imagedata/9098/9098.png)
0 Comment(s)