Add annotations and Polyline to MapView in Swift

In this article, we will see the instructions for adding annotation to MapView, Draw Polylines and Zoom to a region in Swift. Let us see this by adding stations to a Map for Chennai subrban trains and connect these stations using Map Overlay.

Project Setup


Create a new project by selecting Single View Application as the project template.

Enter the required information such project name, organization identifier etc.. as shown in the below screenshot. Then save the project in your desired location.

Add MapKit View


Navigate to Project navigator and select Main.storyboard file.

We are not using the Auto Layout for this demo, hence disable Use Auto Layout and disable size classes using the options available as part of the File Inspector

Drag and drop MapKit View from object library to the View Controller and make sure to resize the MapView to full view. Add IBOutlet in the ViewController for the MapKit and connect it to the MapKit View in the Interface builder. Also add import MapKit to include MapKit framework for your project.

@IBOutlet weak var mapView: MKMapView!

Now if you do a build and run the project in iPhone 6 simulator, you should see the following on simulator.

Zoom to specified region


Add the follwing piece of code in ViewController.swift file. And call this function from ViewController’s viewDidLoad function.

//MARK:- Zoom to region

    func zoomToRegion() {

        let location = CLLocationCoordinate2D(latitude: 13.03297, longitude: 80.26518)

        let region = MKCoordinateRegionMakeWithDistance(location, 5000.0, 7000.0)

        mapView.setRegion(region, animated: true)


CLLocationCoordinate2D is created by specifying latitude and longitude of the zoom location. Then using MKCoordinateRegionMakeWithDistance set the distance around the speicifed location. Then this region will set as the region for the MapView. Build and run the project should show Map zooming to the speicifed region as shown below.


Add plist file to project.


All the station details such as title, latitude and longitude are stored in a plist file. You can download the plist from gitHub. Right click on the Project folder (Project navigator) and select “Add Files to <Project name>” option. And select Copy items if needed option while adding the file.

The sample data structure of the plist file is shown below


Add place holder class Station

Create a new model class for holding the station data. This class should conform to MKAnnotation and NSObject protocol.

import MapKit

class Station: NSObject, MKAnnotation {
    var title: String?
    var subtitle: String?
    var latitude: Double
    var longitude:Double

    var coordinate: CLLocationCoordinate2D {
        return CLLocationCoordinate2D(latitude: latitude, longitude: longitude)

    init(latitude: Double, longitude: Double) {
        self.latitude = latitude
        self.longitude = longitude


This class has properties for title, subtitle, latitude, longitude and coordinate. Any mappoint should have coordinate for the adding it to the map. This property is mandatory and it is defined in MKAnnotation protocol. The initializer in the class accepts the latitide and longitude details as they are needed for creating the coordinates.

Add annotation to MapKit

We need to iterate through the plist file and create annotation for each stations. Add the following function to ViewController.swift which does the same.

//MARK:- Annotations

    func getMapAnnotations() -&gt; [Station] {
        var annotations:Array = [Station]()

        //load plist file
        var stations: NSArray?
        if let path = NSBundle.mainBundle().pathForResource("stations", ofType: "plist") {
            stations = NSArray(contentsOfFile: path)
		//iterate and create annotations
        if let items = stations {
            for item in items {
                let lat = item.valueForKey("lat") as! Double
                let long = item.valueForKey("long")as! Double
                let annotation = Station(latitude: lat, longitude: long)
                annotation.title = item.valueForKey("title") as? String

        return annotations

Add the following piece of code in viewDidLoad function.

let annotations = getMapAnnotations()
// Add mappoints to Map

Now if you build and run the project, you should see the map with annotations. And on tapping any mappoint should display the title for that station.

Add Polyline to MapView

In order add Polyline overlay to map, we need to implement function defined in MKMapViewDelegate protocol. Add MkMapViewDelegate in the class declaration after UIViewController.

class ViewController: UIViewController, MKMapViewDelegate {

Then make sure to set the delegate property of the mapview to self so that the ViewController can implement and handle the MKMapViewDelegate functions. Add the following piece of code in viewDidLoad function after the annotations.

mapView.delegate = self
// Connect all the mappoints using Poly line.

 var points: [CLLocationCoordinate2D] = [CLLocationCoordinate2D]()

  for annotation in annotations {
  var polyline = MKPolyline(coordinates: &amp;points, count: points.count)

create a array of CLLocationCoordinate2D by iterating through annotations. Then create an instance of MKPolyline class by passing array of CLLocationCoordinate2D and count of coordinates. Finally add this polyline to mapView overlay.

Implement the rendererForOverlay MKMapViewDelegate function and return an insatnce of MKPolylineRenderer class

//MARK:- MapViewDelegate methods

    func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -&gt; MKOverlayRenderer! {
        if overlay is MKPolyline {
            var polylineRenderer = MKPolylineRenderer(overlay: overlay)
            polylineRenderer.strokeColor = UIColor.blueColor()
            polylineRenderer.lineWidth = 5
            return polylineRenderer

        return nil


Now build and run the app should display the Polyline on the Map.

Download the source code from here

In Category: Programming, Swift, Xcode

Ravi Shankar

A polyglot software developer and now exploring Swift and iOS development. If you would like to learn from me then check out services page.

Show 13 Comments
  • Vineeth Vijayn October 28, 2015, 5:41 am

    Thanks a great post!!!

    Will it be possible to move an annotation between 2 points?

    Like if I give a start point and end point an annotation should move repeatedly between those 2 points,

    Will it be possible?

  • Freddie December 6, 2015, 7:29 pm

    Thank you wonderful article but I see a couple raw html symbols marring the examples you might want to clear up. (&amp and &-gt;) for example.

  • Keenan January 7, 2016, 4:20 pm

    I get an warning in the rendererForOverlay method because of the force unwraps. Just wondering if there’s something I can do to fix this.

    • Ravi Shankar January 7, 2016, 4:57 pm

      It is fixed now, can you please try the latest source.

  • honestraj February 6, 2016, 6:47 am

    ya it is very nice..
    i want to set a buttons in each and every annotation pins{title,subtitle and button}.
    as it is possible

  • Monal February 8, 2016, 11:31 am

    I’m sorry, I’m new to development but what is plist and where can I find this plist from github.

  • karan February 18, 2016, 7:02 am

    func getMapAnnotations() -> [Station] {

    i am not able to understand ” ->” and xcode is also showing error on this line.

    • Ravi Shankar February 18, 2016, 9:29 am

      It means it is a return parameter, please try to replace with hyphen and greater than sign ->

  • haJT March 13, 2016, 8:23 pm

    Hi, thanx for the great tutorial.

    I understand the code but am have trouble trying to do the same thing when a navigator bar button item was pressed.

    I placed the code of viewdidLoad from
    // Connect all the mappoints using Poly line. and later
    to the button’s action section without forgetting to
    call getMapAnnotations().
    But when I tap the button the app fails and shows a EXC_BAD.

    Besides that I am trying to erase the annotation pins by a different navigation bar button item. It does not work too.

    Could you be kind enough to give me a advice?

  • ed March 17, 2016, 2:26 am

    How would i change the code so it does not show all the pins but a user can enter the title in a search box and then the map would show the pin. I feel I am close but am going crazy trying to add this. Please help 🙂 Thanks

Leave a Comment