Launching the iOS Maps App in Transit Mode - Maps and Location - iOS 9 Swift Programming Cookbook (2015)

iOS 9 Swift Programming Cookbook (2015)

Chapter 8. Maps and Location

8.7 Launching the iOS Maps App in Transit Mode

Problem

You want to launch iOS’s maps app in transit mode.

Solution

When calling the openMapsWithItems(_:launchOptions:) class method of MKMapItem, in the options collection, set the value of the MKLaunchOptionsDirectionsModeKey key to MKLaunchOptionsDirectionsModeTransit.

Discussion

Let’s create a single view controller app and place a button on the view controller to open a map. Set the title of this button to something like “Open maps app in transit mode”. Then hook it up to your view controller. For every coordinate of type CLLocationCoordinate2D, you have to create an instance of MKPlacemark and then from the placemark, create an instance of MKMapItem.

Here is the source map item:

let srcLoc = CLLocationCoordinate2D(latitude: 59.328564,

longitude: 18.061448)

let srcPlc = MKPlacemark(coordinate: srcLoc, addressDictionary: nil)

let src = MKMapItem(placemark: srcPlc)

Followed by the destination map item:

let desLoc = CLLocationCoordinate2D(latitude: 59.746148,

longitude: 18.683281)

let desPlc = MKPlacemark(coordinate: desLoc, addressDictionary: nil)

let des = MKMapItem(placemark: desPlc)

NOTE

You can use the Get Latitude Longitude web site to find the latitude and longitude of any point on the map.

Now we can launch the app, under transit mode, with the source and the destination points:

let options = [

MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeTransit

]

MKMapItem.openMapsWithItems([src, des], launchOptions: options)

See Also