Create MKMapView in Swift Programmatically

In this Swift code example we will create MKMapView programmatically and will add it at the centre of our main view as a subview.

Add MapKit.framework to your project in Xcode

For the code below to work, it is important that you add MapKit.framework to your project. One for the ways to do it is to follow these steps:

  1. Open your project in Xcode and in the left side panel called “Project navigator” select your project. Middle panel of your Xcode will update with new UI.
  2. Then, from the list of Targets(Middle view of your Xcode), select your project name.
  3. From the tabs above(Middle view of your Xcode) select Capabilities
  4. In the list of available Capabilities, Turn on Maps. This will link MapKit.framework to your project.

The code example below will cover:

  • Import MapKit into your Xcode project,
  • Create MKMapView programmatically,
  • Position MKMapView at the specified location within the view
  • Set Map type to MKMapType.Standard
  • Enable map view zoom and scrolling
  • Add MapView as subview

Create and Add MKMapView Programmatically. Complete Code Example in Swift.

import UIKit
import MapKit

class ViewController: UIViewController, MKMapViewDelegate {
    override func viewDidLoad() {
        // Do any additional setup after loading the view, typically from a nib.
    override func didReceiveMemoryWarning() {
        // Dispose of any resources that can be recreated.
    override func viewWillAppear(_ animated: Bool) {
        let mapView = MKMapView()
        let leftMargin:CGFloat = 10
        let topMargin:CGFloat = 60
        let mapWidth:CGFloat = view.frame.size.width-20
        let mapHeight:CGFloat = 300
        mapView.frame = CGRect(x: leftMargin, y: topMargin, width: mapWidth, height: mapHeight)
        mapView.mapType = MKMapType.standard
        mapView.isZoomEnabled = true
        mapView.isScrollEnabled = true
        // Or, if needed, we can position map in the center of the view =

Determine user’s current location latitude and longitude

Also, check out this swift code examples on how to determine user’s current location latitude and longitude.

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

The Complete iOS 10 Developer Course - Build 21 Apps

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:
Facebook: Swift Developer Blog on Facebook