iOS MapKit Getting Started Part #1

Maksym Bilan
3 min readJan 12, 2016

--

Hi, I would like to tell how to work with MapKit in iOS using Swift. This post for beginners, I will try to tell as detailed as possible.

Apple provides MKMapView class for working with map. This class displays maps and provides interface to navigate map content. Detailed documentation about this class you can found here. Let's start.

First of all add the map view to your storyboard or xib, or create from the code. In this sample I will create a simple storyboard with one UIViewController which will contain a map view.

The second main part, you need to add MapKit framework to your project.

If you see the map when you run the application, then you are on the right way.

Please add outlet of a map view object to your UIViewController. Also you need to import a MapKit module in the UIViewController.

import MapKit

Apple provides MKMapViewDelegate and CLLocationManagerDelegate delegates for developers. The MKMapViewDelegate protocol defines a set of optional methods that you can use to receive map-related update messages. Because many map operations require the MKMapView class to load data asynchronously, the map view calls these methods to notify your application when specific operations complete. The map view also uses these methods to request annotation and overlay views and to manage interactions with those views. More details you can found here. The CLLocationManagerDelegate protocol defines the methods used to receive location and heading updates from a CLLocationManager object. More details here.

Don’t forget set up a delegate in your code.

import MapKitclass ViewController: UIViewController, MKMapViewDelegate {  @IBOutlet weak var mapView: MKMapView!  override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
}
}

Or via Interface Builder.

For CLLocationManagerDelegate the same:

locationManager.delegate = self

Let’s try to add button for detecting current location.

let currentLocationButton = UIBarButtonItem(title: "Current Location", style: UIBarButtonItemStyle.Plain, target: self, action: "currentLocationButtonAction:")
self.navigationItem.leftBarButtonItem = currentLocationButton

Then implement currentLocationButtonAction method:

func currentLocationButtonAction(sender: UIBarButtonItem) {
if (CLLocationManager.locationServicesEnabled()) {
if locationManager == nil {
locationManager = CLLocationManager()
}
locationManager?.requestWhenInUseAuthorization()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
}

After that when you requested location, you need to implement didUpdateLocations from CLLocationManagerDelegate, and here you can add location to the map view. Please see the next code:

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last
let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.mapView.setRegion(region, animated: true) if self.mapView.annotations.count != 0 {
annotation = self.mapView.annotations[0]
self.mapView.removeAnnotation(annotation)
}
let pointAnnotation = MKPointAnnotation()
pointAnnotation.coordinate = location!.coordinate
pointAnnotation.title = ""
mapView.addAnnotation(pointAnnotation)
}

Important note: The current authorization status for location data is available from the authorizationStatus class method of CLLocationManager. In requesting authorization in iOS 8 and later, you must use the requestWhenInUseAuthorization or requestAlwaysAuthorization method and include the NSLocationWhenInUseUsageDescription or NSLocationAlwaysUsageDescription key in your Info.plist file to indicate the level of authorization you require.

Full example you can found here.

Happy coding!

--

--

Maksym Bilan
Maksym Bilan

Written by Maksym Bilan

Software Engineer at @MySwimPro |  swift/objc/c++ | 🇺🇦 | family 👨‍👩‍👧 | swimmer 🏊‍♂️ | optimist ⚡️ | superhero for my 👧

No responses yet