Google Maps iOS SDK, Getting Directions between 2 locations

前端 未结 11 1293
栀梦
栀梦 2020-12-02 07:52

While I am using Google Maps SDK, I am trying to get driving direction between two locations on iOS. I know we can do this using two methods:-

1.) Using URL Scheme,

11条回答
  •  温柔的废话
    2020-12-02 08:38

    Swift 4.1, Xcode 9.4.1

    //Here you need to set your origin and destination points and mode 
    let url = NSURL(string: "https://maps.googleapis.com/maps/api/directions/json?origin=Machilipatnam&destination=Vijayawada&mode=driving")
    
    //OR if you want to use latitude and longitude for source and destination
    //let url = NSURL(string: "\("https://maps.googleapis.com/maps/api/directions/json")?origin=\("17.521100"),\("78.452854")&destination=\("15.1393932"),\("76.9214428")")
    
            let task = URLSession.shared.dataTask(with: url! as URL) { (data, response, error) -> Void in
    
                do {
                    if data != nil {
                        let dic = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableLeaves) as!  [String:AnyObject]
    //                        print(dic)
    
                        let status = dic["status"] as! String
                        var routesArray:String!
                        if status == "OK" {
                            routesArray = (((dic["routes"]!as! [Any])[0] as! [String:Any])["overview_polyline"] as! [String:Any])["points"] as! String
    //                            print("routesArray: \(String(describing: routesArray))")
                        }
    
                        DispatchQueue.main.async {
                            let path = GMSPath.init(fromEncodedPath: routesArray!)
                            let singleLine = GMSPolyline.init(path: path)
                            singleLine.strokeWidth = 6.0
                            singleLine.strokeColor = .blue
                            singleLine.map = mapView
                        }
    
                    }
                } catch {
                    print("Error")
                }
            }
    
            task.resume()
    

    Here, you need to add your key (google api key) to the above API.

提交回复
热议问题