Displaying User Location with MapKit

Learn how to use MapKit and CoreLocation to get the user's current location and display it on a map in your Swift application.

Displaying User Location with MapKit

Note:

This tutorial covers how to integrate Apple Maps into your app using MapKit and how to get and show the user's current location using CoreLocation.

Overview

You can use the MapKit framework to handle map-related operations in your project. It provides a simple way to display maps, show user location, add annotations, and more.

Reference:

Step 1: Adding a MapKit View to Your Project

You can start by adding a Map Kit View from the Object Library to your Storyboard and connecting it to the relevant UIViewController as an outlet.

Adding a MapKit View

When you add the Map Kit View, you might encounter the error "Cannot find type ‘MKMapView’ in scope". This is because MKMapView is not part of UIKit. You can solve this by importing the MapKit framework at the top of your ViewController file.

import MapKit

To complete the setup, you must set the MKMapViewDelegate. Add it to your class declaration and set the delegate in viewDidLoad.

class ViewController: UIViewController, MKMapViewDelegate {
    // ...
}

// In viewDidLoad()
mapView.delegate = self

Step 2: Getting the User's Location

To get the user's location, we need to use another framework: CoreLocation.

1. Import CoreLocation and Set Up CLLocationManager

Import CoreLocation and create an instance of CLLocationManager. This class is the central point for configuring and managing location services.

import CoreLocation

class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
    var locationManager = CLLocationManager()
    // ...
}

You'll also need to add CLLocationManagerDelegate to your class declaration and set the delegate in viewDidLoad.

// In viewDidLoad()
locationManager.delegate = self

2. Configure Location Manager Properties

In viewDidLoad, you can configure the location manager's accuracy and request permission from the user.

// Set the desired accuracy
locationManager.desiredAccuracy = kCLLocationAccuracyBest

// Request permission to access location when the app is in use
locationManager.requestWhenInUseAuthorization()

// Start updating the location
locationManager.startUpdatingLocation()
Location Manager Configuration

3. Add Privacy Description to Info.plist

Don't forget to add a description for the location permission request in your Info.plist file. Add a new key called "Privacy - Location When In Use Usage Description" and provide a string explaining why your app needs the user's location.

4. Implement the Delegate Method

The CLLocationManagerDelegate has a method called locationManager(_:didUpdateLocations:) that gets called whenever a new location update is available. This is where we'll get the user's coordinates.

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    // locations.first contains the most recent location
    if let firstLocation = locations.first {
        let latitude = firstLocation.coordinate.latitude
        let longitude = firstLocation.coordinate.longitude
        print("Latitude: \(latitude), Longitude: \(longitude)")
    }
}
didUpdateLocations implementation

Step 3: Centering the Map on the User's Location

Now that we have the user's location, we can tell the MKMapView to center on it. We'll modify the didUpdateLocations function to do this.

  1. Create a CLLocationCoordinate2D object from the user's latitude and longitude.
  2. Create an MKCoordinateSpan to define the zoom level of the map. Smaller values mean a closer zoom.
  3. Create an MKCoordinateRegion using the center coordinate and the span.
  4. Call setRegion on your map view to apply the changes.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.first {
        let userLocation = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
        
        let span = MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
        
        let region = MKCoordinateRegion(center: userLocation, span: span)
        
        mapView.setRegion(region, animated: true)
    }
}

Now, when your app gets a location update, the map will automatically center on the user's current position.


Note:

When using the simulator, you can mock location data by going to Features > Location in the Simulator's menu bar.

Simulator Location Settings