Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw routes between two locations in google maps iOS swift

I'm using google maps in my iOS swift project. I want to draw a path between two locations on the map (Not straight line). Any idea how to do that ?

like image 996
Anushka Madushan Avatar asked Feb 09 '17 12:02

Anushka Madushan


People also ask

Can you draw a route on Google Maps IOS?

You can trace a path or highlight an area on your map by drawing lines and shapes.

Can you draw routes on Google Maps?

Add line or shape.Select a layer and click where to start drawing. A layer can have 2,000 lines, shapes or places. Click each corner or bend of your line or shape. To move the map, click and hold the mouse.


1 Answers

To draw polyline between two locations on Google Map in Swift.

//Pass your source and destination coordinates in this method.

func fetchRoute(from source: CLLocationCoordinate2D, to destination: CLLocationCoordinate2D) {
    
    let session = URLSession.shared
    
    let url = URL(string: "http://maps.googleapis.com/maps/api/directions/json?origin=\(source.latitude),\(source.longitude)&destination=\(destination.latitude),\(destination.longitude)&sensor=false&mode=driving")!
    
    let task = session.dataTask(with: url, completionHandler: {
        (data, response, error) in
        
        guard error == nil else {
            print(error!.localizedDescription)
            return
        }
        
        guard let jsonResult = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any], let jsonResponse = jsonResult else {
            print("error in JSONSerialization")
            return
        }
        
        guard let routes = jsonResponse["routes"] as? [Any] else {
            return
        }
        
        guard let route = routes[0] as? [String: Any] else {
            return
        }

        guard let overview_polyline = route["overview_polyline"] as? [String: Any] else {
            return
        }
        
        guard let polyLineString = overview_polyline["points"] as? String else {
            return
        }
        
        //Call this method to draw path on map
        self.drawPath(from: polyLineString)
    })
    task.resume()
}

To draw polyline on map .

func drawPath(from polyStr: String){
    let path = GMSPath(fromEncodedPath: polyStr)
    let polyline = GMSPolyline(path: path)
    polyline.strokeWidth = 3.0
    polyline.map = mapView // Google MapView
}
like image 132
Ashish Shah Avatar answered Sep 16 '22 15:09

Ashish Shah