MapKit Tutorial with Swift in iOS8

Using Map Kit, the portion of the map that is displayed on the screen is referred to as the region. The region is defined by a center location and  a span of the surrounding area to be displayed. Inside the Map View an annotation could be created, indication a Point of Interest. In this tutorial we will display  a portion of the city London and we will add an annotation of the Big Ben. This tutorial makes use of Xcode 6 and is build for iOS8.

Open Xcode and create a new Single View Application. For product name, use iOS8SwiftMApKitTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.

Go to the storyboard. In Xcode 6 view controllers are now square by default, so that you can create one user interface use just for multiple devices. In iOS8 you can layout the storyboard using constraints and size classes. Since this app is only going to be for the iPhone, you can disable size classes. In the File Inspector untick Use Size Classes.

Choose Keep size class data for: iPhone, and click Disable Size Classes.

Drag a MapKit View  to the main View. Give the MapKit View the same size as its parent view. The StoryBoard should look like this.

Select the Assistant Editor and open ViewController.swift. Ctrl and drag from the Segmented Control to the ViewController.swift and create the following Outlet.

Go to the ViewController.swift file and import the MapKit framework at the top of the file

import MapKit

Change the viewDidLoad method in 

override func viewDidLoad() {
    // 1
    let location = CLLocationCoordinate2D(
      latitude: 51.50007773,
      longitude: -0.1246402
    // 2
    let span = MKCoordinateSpanMake(0.05, 0.05)
    let region = MKCoordinateRegion(center: location, span: span)
    mapView.setRegion(region, animated: true)
    let annotation = MKPointAnnotation()
    annotation.coordinate = location
    annotation.title = "Big Ben"
    annotation.subtitle = "London"
  1. The latitude and longitude of the city of London is assigned to location constant using the CLLocationCoordinate2d struct 
  2. The span value is made relative small, so a big portion of London is visible. The MKCoordinateRegion method defines the visible region, it is set with the setRegion method.
  3. An annotation is created at the current coordinates with the MKPointAnnotaition class. The annotation is added to the Map View with the addAnnotation method.

Build and Run the project, The city of London, including the annotation will be diplayed.

You can download the source code of the iOS8SwiftMapKitTutorial at the ioscreator repository on github.