Apple’s MapKit makes it very easy to get directions from one coordinate to another. Let us see how to use this to show a route on an MKMapView.
First, make the ViewController conform to the MKMapViewDelegate protocol.
and make sure the outlet of the map view is attached and the delegate is set.
mapView.delegate = self
Now write this method for showing the route. This method performs the following actions
- Takes 2 coordinates as parameters
- Fetches direction between the 2 points
- Displays the fetched route on the map
- Zooms the map to the route area.
func showRouteOnMap(pickupCoordinate: CLLocationCoordinate2D, destinationCoordinate: CLLocationCoordinate2D) { let request = MKDirections.Request() request.source = MKMapItem(placemark: MKPlacemark(coordinate: pickupCoordinate, addressDictionary: nil)) request.destination = MKMapItem(placemark: MKPlacemark(coordinate: destinationCoordinate, 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 getting just one route if let route = unwrappedResponse.routes.first { //show on map self.mapView.addOverlay(route.polyline) //set the map area to show the route self.mapView.setVisibleMapRect(route.polyline.boundingMapRect, edgePadding: UIEdgeInsets.init(top: 80.0, left: 20.0, bottom: 100.0, right: 20.0), animated: true) } //if you want to show multiple routes then you can get all routes in a loop in the following statement //for route in unwrappedResponse.routes {} } }
Also, write the following delegate function to render the line showing the route. This can be customised in color and width according to your preference.
//this delegate function is for displaying the route overlay and styling it func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { let renderer = MKPolylineRenderer(overlay: overlay) renderer.strokeColor = UIColor.red renderer.lineWidth = 5.0 return renderer }
Now, let us call this with some sample coordinates from our viewDidLoad method.
//create two dummy locations let loc1 = CLLocationCoordinate2D.init(latitude: 40.741895, longitude: -73.989308) let loc2 = CLLocationCoordinate2D.init(latitude: 40.728448, longitude: -73.717996) //find route showRouteOnMap(pickupCoordinate: loc1, destinationCoordinate: loc2)
You should be able to see a route on the map now!
…
Leave A Comment