Swift — Display route between two coordinates on Google Map / GMSMapView, using MapKit — MKDirections

Zeba Rahman
fabcoding
Published in
2 min readAug 3, 2020

This tutorial shows, in a Swift app, how we can use MapKit’s free direction service MKDirections, to get a route between two coordinates and show the resulting route on a Google Map, GMSMapView.

First, get this file, and save it within your project as Polyline.swift. This will be used to create Polyline from coordinates:

Second, use the two coordinates and pin markers on the points.

import UIKit
import GoogleMaps
import MapKit
func setMapMarkersRoute(vLoc: CLLocationCoordinate2D, toLoc: CLLocationCoordinate2D) {

//add the markers for the 2 locations
let markerTo = GMSMarker.init(position: toLoc)
markerTo.map = mapView
let vMarker = GMSMarker.init(position: vLoc)
vMarker.map = mapView

//zoom the map to show the desired area
var bounds = GMSCoordinateBounds()
bounds = bounds.includingCoordinate(vLoc)
bounds = bounds.includingCoordinate(toLoc)
self.mapView.moveCamera(GMSCameraUpdate.fit(bounds))

//finally get the route
getRoute(from: vLoc, to: toLoc)

}

Third, the function to get the directions using MKDirections

func getRoute(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D) {

let source = MKMapItem(placemark: MKPlacemark(coordinate: from))
let destination = MKMapItem(placemark: MKPlacemark(coordinate: to))

let request = MKDirections.Request()
request.source = source
request.destination = destination
request.requestsAlternateRoutes = false

let directions = MKDirections(request: request)

directions.calculate(completionHandler: { (response, error) in
if let res = response {
//the function to convert the result and show
self.show(polyline: self.googlePolylines(from: res))
}
})
}

Fourth, converting the result from MKDirections, to GMSPolyline, that can be used with GMSMapView

private func googlePolylines(from response: MKDirections.Response) -> GMSPolyline {

let route = response.routes[0]
var coordinates = [CLLocationCoordinate2D](
repeating: kCLLocationCoordinate2DInvalid,
count: route.polyline.pointCount)

route.polyline.getCoordinates(
&coordinates,
range: NSRange(location: 0, length: route.polyline.pointCount))

let polyline = Polyline(coordinates: coordinates)
let encodedPolyline: String = polyline.encodedPolyline
let path = GMSPath(fromEncodedPath: encodedPolyline)
return GMSPolyline(path: path)

}

Fifth, finally show it on the GMSMapView

func show(polyline: GMSPolyline) {

//add style to polyline
polyline.strokeColor = UIColor.red
polyline.strokeWidth = 3

//add to map
polyline.map = mapView
}

Make sure you have created an outlet to the GMSMapView.

Hope this helps. If you need assistance, feel free to leave a comment!

Originally published at Fabcoding.

--

--