How to draw a route between two locations using MapKit in Swift?


To draw a route between two Locations on map we need to have co-ordinates of both those locations.

Once we have the co-ordinates of both locations we can use the below given function to show the line between two points on map. In this example I’ll be using two random location as two points.

func getDirections(loc1: CLLocationCoordinate2D, loc2: CLLocationCoordinate2D) {
   let source = MKMapItem(placemark: MKPlacemark(coordinate: loc1))
   source.name = "Your Location"
   let destination = MKMapItem(placemark: MKPlacemark(coordinate: loc2))
   destination.name = "Destination"
   MKMapItem.openMaps(with: [source, destination], launchOptions: [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving])
}

We’ll call this function in ViewDidLoad for this tutorial to show the result but you may use it as per your need.

Before that we’ll have to create two locations.

override func viewDidLoad() {
   super.viewDidLoad()
   let coordinateOne = CLLocationCoordinate2D(latitude: CLLocationDegrees(exactly: 40.586746)!, longitude: CLLocationDegrees(exactly: -108.610891)!)
   let coordinateTwo = CLLocationCoordinate2D(latitude: CLLocationDegrees(exactly: 42.564874)!, longitude: CLLocationDegrees(exactly: -102.125547)!)
   self.getDirections(loc1: coordinateOne, loc2: coordinateTwo)
}

When we run the above code on the device the following output is given

Updated on: 30-Jul-2019

692 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements