#48: MKDirections 🚩


MKDirections and MKDirectionsRequest are the classes we use to retrieve directions between two locations. They also make it very easy to display the resulting directions route on a map. Let's dive in:

Setup Directions Request

Note: Off camera, we have let the user input a keyword search String, then geocoded it into an MKPlacemark object called placemark.

let request = MKDirectionsRequest()

request.source = MKMapItem.mapItemForCurrentLocation()

let destination = MKPlacemark(
  coordinate: placemark.location.coordinate,
  addressDictionary: nil

request.destination = MKMapItem(placemark: destination)
let d = MKDirections(request: request)

d.calculateDirectionsWithCompletionHandler { response, error in
  guard let route = response?.routes.first else { return }

  // we'll do this bit next

Display Directions on Map

self.directionsRoute = route

  animated: true

Finally, we implement this MKMapViewDelegate method:

func mapView(mapView: MKMapView,
rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
  let renderer = MKPolylineRenderer(
    polyline: directionsRoute.polyline

  renderer.lineWidth = 2
  renderer.strokeColor = UIColor.blueColor()

  return renderer