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

前端 未结 5 1069
北海茫月
北海茫月 2021-02-04 13:31

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 ?

5条回答
  •  日久生厌
    2021-02-04 13:40

    This piece of code will work right for you. Don't forget to change your API key and mode (walking, driving).

    func draw(src: CLLocationCoordinate2D, dst: CLLocationCoordinate2D){
    
        let config = URLSessionConfiguration.default
        let session = URLSession(configuration: config)
    
        let url = URL(string: "https://maps.googleapis.com/maps/api/directions/json?origin=\(src.latitude),\(src.longitude)&destination=\(dst.latitude),\(dst.longitude)&sensor=false&mode=walking&key=**YOUR_KEY**")!
    
        let task = session.dataTask(with: url, completionHandler: {
            (data, response, error) in
            if error != nil {
                print(error!.localizedDescription)
            } else {
                do {
                    if let json : [String:Any] = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any] {
    
                        let preRoutes = json["routes"] as! NSArray
                        let routes = preRoutes[0] as! NSDictionary
                        let routeOverviewPolyline:NSDictionary = routes.value(forKey: "overview_polyline") as! NSDictionary
                        let polyString = routeOverviewPolyline.object(forKey: "points") as! String
    
                        DispatchQueue.main.async(execute: {
                            let path = GMSPath(fromEncodedPath: polyString)
                            let polyline = GMSPolyline(path: path)
                            polyline.strokeWidth = 5.0
                            polyline.strokeColor = UIColor.green
                            polyline.map = mapView    
                        })
                    }
    
                } catch {
                    print("parsing error")
                }
            }
        })
        task.resume()
    }
    

提交回复
热议问题