How can I draw a route between user\'s current location to a specific location using MapKit in Swift?
I searched a lot, but didn\'t find any helpful
class MapController: UIViewController, MKMapViewDelegate {
func showRouteOnMap() {
let request = MKDirectionsRequest()
request.source = MKMapItem(placemark: MKPlacemark(coordinate: annotation1.coordinate, addressDictionary: nil))
request.destination = MKMapItem(placemark: MKPlacemark(coordinate: annotation2.coordinate, addressDictionary: nil))
request.requestsAlternateRoutes = true
request.transportType = .Automobile
let directions = MKDirections(request: request)
directions.calculateDirectionsWithCompletionHandler { [unowned self] response, error in
guard let unwrappedResponse = response else { return }
if (unwrappedResponse.routes.count > 0) {
self.mapView.addOverlay(unwrappedResponse.routes[0].polyline)
self.mapView.setVisibleMapRect(unwrappedResponse.routes[0].polyline.boundingMapRect, animated: true)
}
}
}
func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
if overlay is MKPolyline {
var polylineRenderer = MKPolylineRenderer(overlay: overlay)
polylineRenderer.strokeColor = UIColor.blueColor()
polylineRenderer.lineWidth = 5
return polylineRenderer
}
return nil
}
The return is an array of possible routes, usually we just want to show the first. The annotations are the map annotations.