loading...
Cover image for MapKit — User Current Location

MapKit — User Current Location

muneebaliarshad profile image Muneeb Ali Arshad ・3 min read

In this article will discuss how to use MapKit and get the current location of the device in swift. If I missed something let me know in comments.

Location

Let’s get started:

First, we will create a project in Xcode and then go to the storyboard and then add MapKit from tools to the UIViewController.
Mapkit Tool
Now run the application you will see the map like this
MapKit on Simulator

Current Location:

Create an outlet of the MapKit in the UIViewController class this map view is inherited from MKMapView and then we have to import MapKit.

import MapKit

Now create location Manager variable (CLLocationManager) global so we can use in class easily.

fileprivate let locationManager: CLLocationManager = {
    let manager = CLLocationManager()
    manager.requestWhenInUseAuthorization()
    return manager
}()

and then use this function to get the current location.

func currentLocation() {
   locationManager.delegate = self
   locationManager.desiredAccuracy = kCLLocationAccuracyBest
   if #available(iOS 11.0, *) {
      locationManager.showsBackgroundLocationIndicator = true
   } else {
      // Fallback on earlier versions
   }
   locationManager.startUpdatingLocation()
}

Now we will implement the CLLocationManagerDelegate Methods:

extension ViewController: CLLocationManagerDelegate {
   func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

      let location = locations.last! as CLLocation
      let currentLocation = location.coordinate
      let coordinateRegion = MKCoordinateRegion(center: currentLocation, latitudinalMeters: 800, longitudinalMeters: 800)
      mapView.setRegion(coordinateRegion, animated: true)
      locationManager.stopUpdatingLocation()
   }

   func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
      print(error.localizedDescription)
   }
}

Now you have to add following lines of code in info.plist. These keys are used to getting permission from the user and it’s necessary also because Apple doesn’t approve the application without this and neither current location will be accessible. Use proper description as required in your project.

<key>NSLocationAlwaysUsageDescription</key>
<string>This Application Use your current location</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>This Application Use your current location</string>

Now build and run the application
User Current Location

If you are using the simulator as I am so by allowing permission you can’t see the current location pin on the map because the simulator doesn’t have access to it as a real device. Then for accessing it, you have to set the dummy current location from Xcode then it will show the current location pin on the map.
Dummy Location

Current Location

The full code of the current implementation of the map is :

import UIKit
import MapKit
class ViewController: UIViewController {
     //MARK: - IBOutlets
     @IBOutlet weak var mapView: MKMapView!
     //MARK: - Variables
     fileprivate let locationManager: CLLocationManager = {
        let manager = CLLocationManager()
        manager.requestWhenInUseAuthorization()
        return manager
     }()
     //MARK: - UIViewController life Cycle Methods
     override func viewDidLoad() {
        super.viewDidLoad()
        setUpMapView()
     }

     //MARK: - Setup Methods
     func setUpMapView() {
        mapView.showsUserLocation = true
        mapView.showsCompass = true
        mapView.showsScale = true
        currentLocation()
     }

     //MARK: - Helper Method
     func currentLocation() {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        if #available(iOS 11.0, *) {
           locationManager.showsBackgroundLocationIndicator = true
        } else {
           // Fallback on earlier versions
        }
        locationManager.startUpdatingLocation()
     }
}

//MARK: - CLLocationManagerDelegate Methods
extension ViewController: CLLocationManagerDelegate {
     func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let location = locations.last! as CLLocation
        let currentLocation = location.coordinate
        let coordinateRegion = MKCoordinateRegion(center: currentLocation, latitudinalMeters: 800, longitudinalMeters: 800)
        mapView.setRegion(coordinateRegion, animated: true)
        locationManager.stopUpdatingLocation()
     }

     func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error.localizedDescription)
     }
}

Posted on by:

muneebaliarshad profile

Muneeb Ali Arshad

@muneebaliarshad

I am an iOS developer with 4 years of experience, during this period I was involved in the development of such products as geolocation, music and video application, messengers, and social media apps.

Discussion

pic
Editor guide