NEW! Pre-order my latest book, Testing Swift! >>

How to find directions using MKMapView and MKDirectionsRequest

Paul Hudson       @twostraws

MapKit is great for letting users navigate from place to place, but also makes it easy for you to plot directions from one place to another. You just tell iOS where you're starting from, where you're going, as well as how you're traveling (by car, foot, or mass transit), and it will find routes for you.

First, make sure you have a map view in your app, and have the Maps entitlement enabled. Now add this code:

import MapKit
import UIKit

class ViewController: UIViewController, MKMapViewDelegate {
    @IBOutlet var mapView: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let request = MKDirectionsRequest()
        request.source = MKMapItem(placemark: MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: 40.7127, longitude: -74.0059), addressDictionary: nil))
        request.destination = MKMapItem(placemark: MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: 37.783333, longitude: -122.416667), addressDictionary: nil))
        request.requestsAlternateRoutes = true
        request.transportType = .automobile

        let directions = MKDirections(request: request)

        directions.calculate { [unowned self] response, error in
            guard let unwrappedResponse = response else { return }

            for route in unwrappedResponse.routes {
                self.mapView.add(route.polyline)
                self.mapView.setVisibleMapRect(route.polyline.boundingMapRect, animated: true)
            }
        }
    }

    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        let renderer = MKPolylineRenderer(polyline: overlay as! MKPolyline)
        renderer.strokeColor = UIColor.blue
        return renderer
    }
}

That example requests driving directions between New York and San Francisco. It asks for alternate routes if they exist (spoiler: they do), then sets up a closure to run when the directions come back that adds them as overlays to the map. To make the overlays draw, you need to implement the rendererFor method, but that's just three lines as you can see.

Note: because I request alternative routes if they exist, I loop through the array of returned routes to add them all to the map. The setVisibleMapRect() method is called once for each route, but fortunately that isn't a problem as all routes have the same start and end location!

Available from iOS 6.0

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Want to build macOS apps?

Hacking with macOS delivers 18 awesome projects that teach you macOS development in no time – take control of your desktop today!

MASTER SWIFT NOW
Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Practical iOS 11 Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Average rating: 3.0/5

Click here to visit the Hacking with Swift store >>