MapKit iOS Tutorial

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 is made with Xcode 10 and built for iOS 12.

Project Setup

Open Xcode and create a new Single View App.

For product name, use IOSMapKitTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

Storyboard Setup

Go to the storyboard. Drag a MapKit View  to the main View. Give the MapKit View the same size as the main View. Select the MapKit View and go to the Pin button from the Auto Layout button on the bottom-right of the Storyboard and fill in the following values. Select Add 4 Constraints.

The Storyboard should look like this.

Outlet Connections

Select the Assistant Editor and make sure the ViewController.swift file is visible. Ctrl-drag or right-click-drag from the Map view to inside the ViewController class and create the following Outlet.

Code Implementation 

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() {
    super.viewDidLoad()
    // 1
    let location = CLLocationCoordinate2D(latitude: 51.50007773,
        longitude: -0.1246402)
    
    // 2
    let span = MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
    let region = MKCoordinateRegion(center: location, span: span)
        mapView.setRegion(region, animated: true)
        
    //3
    let annotation = MKPointAnnotation()
    annotation.coordinate = location
    annotation.title = "Big Ben"
    annotation.subtitle = "London"
    mapView.addAnnotation(annotation)
}
  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 MKPointAnnotation class. The annotation is added to the Map View with the addAnnotation method.

Run Project

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

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

Related Articles