Introduction to draw route on iOS map (MapKit) using MKDirections in swift4
In this tutorial, we are going to learn how to to draw route on MapKit (apple map) between two locations using swift4 language. We will use MKAnnotation’s to draw pins for source and destination. For getting route, we will use MKDirection class and then draw polyline (commonly known as route) on the MKMapView. Follow the below given steps to learn how we can draw route between two points on MKMapView in swift4.
Steps to draw route on MKMapView
Step 1: Create a new single view project, name it “DrawRouteOnMapKit”. Open “Main.storyboard” and drag ‘Map kit view’, aka mapview on to view.
Step 2: Open “ViewController.swift”, create IBOutlet for the map kit view we added in last step.
Step 3: Open “Main.storyboard”, connect IBOutlet to the mapkitview created in step 1.
Step 4: Open “ViewController.swift”, now its time to create class for the pins or MKAnnotations that will act as pole for source and destination location. Below is the code for creating custom class for MKAnnotation.
Step 5: As we successfully created custom class for our pin or annotation. It’s time to get directions between two locations and draw route on Mapkit aka mapview. In ViewDidLoad, first we will create coordinates for source location and destination location.
Adding pins to source and destination
Step 6: Now we will use our custom MKAnnotation class to create pins for source and destination locations with the coordinates set in the last step.
Step 7: If you run the app at this moment, you will see two pins on that map (Please go to USA on the map by zooming or pinching on it if your current location is far from USA, because we set source and destination of two cities of USA).
Step 8: In order to get directions for routes between our two locations, we need to create a placmark using MKPlaceMark class which accepts coordinate. We will create two placmarks for source location and destination location.
Step 9: To get directions, we will use MKDirectionRequest class. MkDirectionRequest class has properties like source, destination, transportType (mode of of our transport either automobile, walking, transit, any). Lastly, we will use MKDirection class, and request for directions. We will get directions in the callback. Below is the final code
Run the app, at this point you will see pins but no route. For this we need to implement one delegate method of MapKit so that we can render the route or polyline.
Step 10: Set delegate of mapview(MapKit) to self and then implement the delegate method
Where to go from here:
In this tutorial, we learned how to draw route between two location in iOS map (MapKit). You can also download source code from https://goo.gl/tmi4es