MapView – Display User’s Current Location and Drop a Pin

In this video tutorial I am going to share with you how to display user’s current location on a MapView programmatically as well as how to create MapView using Xcode Storyboard. We will also learn how to drop a Pin(MKPointAnnotation) at user’s current location and set MKPointAnnotation custom title.

MapView example in Swift

For your application to be able to determine user’s current location, we will need to update project’s info.plist file.

Update Info.plist file

For your app to be able to request user’s current location, you will need to open Info.plist file as Source Code and add the following two new keys and corresponding values:

 
    NSLocationAlwaysUsageDescription
    Will you allow this app to always know your location?
    NSLocationWhenInUseUsageDescription
    Do you allow this app to know your current location?

Display User’s Current Location on a MapView. Complete Source Code in Swift.

 
import UIKit
import CoreLocation
import MapKit

class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
 
    var locationManager:CLLocationManager!
    var mapView:MKMapView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        // Create and Add MapView to our main view
        createMapView()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        determineCurrentLocation()
    }

    func createMapView()
    {
        mapView = MKMapView()
        
        let leftMargin:CGFloat = 10
        let topMargin:CGFloat = 60
        let mapWidth:CGFloat = view.frame.size.width-20
        let mapHeight:CGFloat = 300
        
        mapView.frame = CGRectMake(leftMargin, topMargin, mapWidth, mapHeight)
        
        mapView.mapType = MKMapType.Standard
        mapView.zoomEnabled = true
        mapView.scrollEnabled = true
        
        // Or, if needed, we can position map in the center of the view
        mapView.center = view.center
        
        view.addSubview(mapView)
    }
    
    func determineCurrentLocation()
    {
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestAlwaysAuthorization()
        
        if CLLocationManager.locationServicesEnabled() {
            //locationManager.startUpdatingHeading()
            locationManager.startUpdatingLocation()
        }
    }
    
    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let userLocation:CLLocation = locations[0] as CLLocation
        
        // Call stopUpdatingLocation() to stop listening for location updates,
        // other wise this function will be called every time when user location changes.
        //manager.stopUpdatingLocation()
        
        let center = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude)
        let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
        
        mapView.setRegion(region, animated: true)
        
        // Drop a pin at user's Current Location
        let myAnnotation: MKPointAnnotation = MKPointAnnotation()
        myAnnotation.coordinate = CLLocationCoordinate2DMake(userLocation.coordinate.latitude, userLocation.coordinate.longitude);
        myAnnotation.title = "Current location"
        mapView.addAnnotation(myAnnotation)
    }
    
    func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
    {
        print("Error \(error)")
    }
 
}

Video Tutorial

I hope this video tutorial was helpful to you. If you are learning Swift, consider the below three video courses which I think might help you a lot.


Learn iOS Development with these Video Courses


How to Make a Freaking iPhone App - iOS 10 and Swift 3
icon icon


iOS 10 & Swift 3: From Beginner to Paid Professional
icon


The Complete iOS 10 Developer Course - Build 21 Apps
icon


Swift 3 - Learn to Code with Apple's New Language
icon icon


Learn How to Build Mobile Apps for iOS with Swift, PHP and MySQL
icon icon

Follow me on one of your favourite social networks to learn about new video tutorials and code examples:

Twitter: @SwiftVideoBlog
Google Plus: https://plus.google.com/+SergeyKargopolov/posts
Facebook: Swift Developer Blog on Facebook



  • Optimization 1

    Thank you for sharing the information…

    android development company

  • ridwan

    I want to ask about the detail view controller, I’ve tried to resolve this error, if you can help me.

  • Nathan

    I got Segmentation fault: 11 while running your exact code for testing