
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Draw 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
Advertisements