Calculate route between two points with Google Maps in IOS


I'm using the SDK of Google Maps in

asked by Awes0meM4n 20.10.2016 в 08:18

3 answers


I found a pretty complete manual for the in which it explains In detail the steps to follow to present the user with the current position, create a route, draw a route, add intermediate locations, etc.

For your case I think that the Drawing a Route section fits pretty well to what you ask, because it shows you the steps to follow to get the route between a start address and an end address and then draw the corresponding route.

The tutorial is the following A Swift Tutorial for Google Maps SDK

Next I put the code that I think can help you where the URL to make the request to WS Google is:

let baseURLDirections = ""

The function that takes care of this is the following:

func getDirections(origin: String!, destination: String!, waypoints: Array<String>!, travelMode: AnyObject!, completionHandler: ((status: String, success: Bool) -> Void)) {
    if let originLocation = origin {
        if let destinationLocation = destination {
            var directionsURLString = baseURLDirections + "origin=" + originLocation + "&destination=" + destinationLocation

            directionsURLString = directionsURLString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!

            let directionsURL = NSURL(string: directionsURLString)

            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                let directionsData = NSData(contentsOfURL: directionsURL!)

                var error: NSError?
                let dictionary: Dictionary<NSObject, AnyObject> = NSJSONSerialization.JSONObjectWithData(directionsData!, options: NSJSONReadingOptions.MutableContainers, error: &error) as Dictionary<NSObject, AnyObject>

                if (error != nil) {
                    completionHandler(status: "", success: false)
                else {
                    let status = dictionary["status"] as String

                    if status == "OK" {
                        self.selectedRoute = (dictionary["routes"] as Array<Dictionary<NSObject, AnyObject>>)[0]
                        self.overviewPolyline = self.selectedRoute["overview_polyline"] as Dictionary<NSObject, AnyObject>

                        let legs = self.selectedRoute["legs"] as Array<Dictionary<NSObject, AnyObject>>

                        let startLocationDictionary = legs[0]["start_location"] as Dictionary<NSObject, AnyObject>
                        self.originCoordinate = CLLocationCoordinate2DMake(startLocationDictionary["lat"] as Double, startLocationDictionary["lng"] as Double)

                        let endLocationDictionary = legs[legs.count - 1]["end_location"] as Dictionary<NSObject, AnyObject>
                        self.destinationCoordinate = CLLocationCoordinate2DMake(endLocationDictionary["lat"] as Double, endLocationDictionary["lng"] as Double)

                        self.originAddress = legs[0]["start_address"] as String
                        self.destinationAddress = legs[legs.count - 1]["end_address"] as String


                        completionHandler(status: status, success: true)
                    else {
                        completionHandler(status: status, success: false)
        else {
            completionHandler(status: "Destination is nil.", success: false)
    else {
        completionHandler(status: "Origin is nil", success: false)
answered by 25.12.2016 в 20:36

This response does not provide a solution using Google services. There are several alternatives to the (limited) Google Maps services. On the one hand we have OpenStreetMaps (OSM) and its OSRM project, which has implemented several services including the service Route Service which is what interests in this case:


Route service


Finds the fastest route between coordinates in the supplied order.

In the documentation you will find certain parameters of interest that you can send in your request. So the solution is as simple as sending an HTTP request with the required information to the OSM service and using the geometries returned by that request.

Another alternative is to have your own cartography and your own server, you could implement your own route service, having as a data repository a PostgreSQL / PostGIS database and having the pgrouting extension. If you had abundant and accurate cartography, real-time data, etc., this would be the solution you would take. It would also take into account the geographical extension for this solution, since the difficulty lies in getting updated road data for the entire area of interest.

Obviously, to do what you want, you are not going to implement your own API. Do some research on OSM services that, apart from being free, have no limitations on use.

answered by 25.12.2016 в 17:55

To return the distance between 2 points you do not need to use any Google API, you can do it natively in iOS with CLLocation all you have to do is implement the following method

import CoreLocation

let Punto1 = CLLocation(latitude: 5.0, longitude: 5.0)
let Punto2 = CLLocation(latitude: 5.0, longitude: 3.0)

let DistanciaEnMetros = Punto1.distance(from: Punto2) 
answered by 20.10.2016 в 15:52