Show a route between two coordinates on GoogleMaps with Swift

For this tutorial, we assume you already have successfully integrated Google Maps into your Swift project, and have a working map in a ViewController. If you are a beginner and need help with these, comment below!

So I always use Alamofire for network calls and SwiftyJSON for parsing, two very convenient tools for Swift apps. And GoogleMaps of course, as we are working with that. So just make sure you have these Pods installed.

pod 'Alamofire'   
pod 'Alamofire-SwiftyJSON'
pod 'GoogleMaps'

Import the necessary packages in your viewcontroller

import GoogleMaps
import Alamofire
import Alamofire_SwiftyJSON

Make sure you have an outlet to your mapView

//outlet to google maps view in your storyboard
@IBOutlet var mapView: GMSMapView!

Now write this method that takes 2 coordinates as parameters and fetches directions from Google Maps API.

Do not forget to replace YOUR_GOOGLE_API_KEY with your actual API KEY from Google. How do I get one?.

func showRouteOnMap(pickupCoordinate: CLLocationCoordinate2D, destinationCoordinate: CLLocationCoordinate2D) {

    let origin = "\(pickupCoordinate.latitude),\(pickupCoordinate.longitude)"
    let destination = "\(destinationCoordinate.latitude),\(destinationCoordinate.longitude)"

    let url = "https://maps.googleapis.com/maps/api/directions/json?origin=\(origin)&destination=\(destination)&mode=driving&key=\(YOUR_GOOGLE_API_KEY)"

    Alamofire.request(url).responseSwiftyJSON { response in

        if let json = response.result.value {
            if let routes = json["routes"].array {
                if let route = routes.first {

                    let routeOverviewPolyline = route["overview_polyline"].dictionary
                    let points = routeOverviewPolyline?["points"]?.string
                    if let path = GMSPath.init(fromEncodedPath: points!) {
                        self.setPath(path: path)
                    }
                }
            }
        }
    }
}

And then, the method for displaying the path on the map.

func setPath(path: GMSPath) {

    var polyline = GMSPolyline.init(path: path)
    polyline.strokeColor = UIColor.colorAccent
    polyline.strokeWidth = 5
    polyline.map = self.mapView

    var bounds = GMSCoordinateBounds()

    for index in 1...path.count() {
        bounds = bounds.includingCoordinate(path.coordinate(at: index))
    }

    self.mapView.moveCamera(GMSCameraUpdate.fit(bounds))

    //optional - get distance of the route in kms!
    let mtrs = GMSGeometryLength(path)
    dist = mtrs/1000.0
    print("The distance of the route is \(dist) km")
    
}

Finally, 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)

//set markers on the two locations
let m1 = GMSMarker.init(position: loc1)
m1.map = mapView
let m2 = GMSMarker.init(position: loc2)
m2.map = mapView

//find route
showRouteOnMap(pickupCoordinate: loc1, destinationCoordinate: loc2)

You should be able to see two markers with a route between them.


Also published on Medium.

By |2020-04-21T14:18:33+00:00April 21st, 2020|Categories: iOS, iOS Tutorials|Tags: |0 Comments

Leave A Comment