MapBox Tutorial for Swift: Maps, Location, Markers/Annotations

Getting Started

Sign up for an account at mapbox.com/signup. Find your access token on your account page.

Create a new iOS Project.

Add the following pod to your Podfile

pod 'Mapbox-iOS-SDK', '~> 4.9'

and run

pod install

Open info.plist file and the following key, with value as the access token you received from MapBox in the first step.

<key>MGLMapboxAccessToken</key>
<string>YOUR_TOKEN</string>

Also, NSLocationWhenInUseUsageDescription is required for apps that use location services. Add this key as well in info.plist.

<key>NSLocationWhenInUseUsageDescription</key>
<string>Allow access to location so that we can show you stations near you and nearest upcoming departures</string>

Adding the map to your ViewController

There are 2 ways to add a map.

  1. Using storyboard
  2. Programmatically

Using Storyboard

Drag a UIView into your ViewController, add necessary constraints, and change its class to MGLMapView

 

For this same UIView/MapView, under the attributes inspector tab, specify the Style URL as mapbox://styles/mapbox/streets-v11

Lastly, create an outlet of this view to your ViewController.swift class.   

 @IBOutlet var mapView: MGLMapView!

Dont forget to import Mapbox in the beginning of the ViewController class.

Programmatically adding map, without using Storyboard

In case you do not wish to use Storyboard to add the map, you can create it this way:
import Mapbox
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let url = URL(string: "mapbox://styles/mapbox/streets-v11")
        let mapView = MGLMapView(frame: view.bounds, styleURL: url)
        mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        mapView.setCenter(CLLocationCoordinate2D(latitude: 59.31, longitude: 18.06), zoomLevel: 9, animated: false)
        view.addSubview(mapView)
    }
}

After adding the map, make your ViewController conform to MGLMapViewDelegate, and set it in viewDidLoad()

mapView.delegate = self

Map location

To show user’s location on the map:

mapView.setUserTrackingMode(.follow, animated: true)

To move the map to a particular co-ordinate,

mapView.setCenter(Constants.qatarcoords, zoomLevel: 10, direction: 0, animated: false)

Annotations 

You may need to show markers on the map. Annotation is a marker that can be placed on the MapBox map.      

let hello = MGLPointAnnotation()
hello.coordinate = CLLocationCoordinate2D(latitude: item.lat, longitude: item.lon)
hello.title = item.title
mapView.addAnnotation(hello)

Using a custom image for annotations

To use your own image in place of the default annotation of MapBox, implement this delegate function.

func mapView(_ mapView: MGLMapView, imageFor annotation: MGLAnnotation) -> MGLAnnotationImage? {
    var annotationImage = mapView.dequeueReusableAnnotationImage(withIdentifier: "mymarker")
    if annotationImage == nil {
            var image = UIImage(named: "mapstad1")!
            //image = image.withAlignmentRectInsets(UIEdgeInsets(top: 0, left: 0, bottom: image.size.height/2, right: 0))
            annotationImage = MGLAnnotationImage(image: image, reuseIdentifier: "mymarker")
        }
        return annotationImage
    } 
}

Callout

To show a callout displaying title and subtitle of the annotation upon click, add this delegate function

func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
   // Always allow callouts to popup when annotations are tapped.
   return true
}

Removing Annotations

To remove an annotation

self.mapView.removeAnnotation(hello)

To remove all annotations from Map

if let annotations = self.mapView.annotations {
    self.mapView.removeAnnotations(annotations)
}

Also published on Medium.

By |2019-04-04T05:17:45+00:00March 25th, 2019|Categories: iOS Tutorials|Tags: , |0 Comments

Leave A Comment