SWIFT: google maps draw waypoint polyline

前端 未结 4 1878
被撕碎了的回忆
被撕碎了的回忆 2021-01-07 09:12

Hi I wonder if there is a method to draw a waypoint between two or more markers in google maps iOS. I don\'t want to draw straight lines... but use just public roads. Here i

4条回答
  •  花落未央
    2021-01-07 09:58

    To draw polyline between two markers on GoogleMap in Swift 3.

    // Pass your source and destination coordinates in this method.
    func getPolylineRoute(from source: CLLocationCoordinate2D, to destination: CLLocationCoordinate2D){
    
            let config = URLSessionConfiguration.default
            let session = URLSession(configuration: config)
    
            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
                if error != nil {
                    print(error!.localizedDescription)
                }else{
                    do {
                        if let json : [String:Any] = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]{
    
                            let routes = json["routes"] as? [Any]
                            let overview_polyline = routes?[0] as?[String:Any]
                            let polyString = overview_polyline?["points"] as?String
    
                            //Call this method to draw path on map
                            self.showPath(polyStr: polyString!)
                        }
    
                    }catch{
                        print("error in JSONSerialization")
                    }
                }
            })
            task.resume()
        }
    

    To draw polyline on map .

    func showPath(polyStr :String){
        let path = GMSPath(fromEncodedPath: polyStr)
        let polyline = GMSPolyline(path: path)
        polyline.strokeWidth = 3.0
        polyline.map = mapView // Your map view
    }
    

提交回复
热议问题