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

前端 未结 5 1082
北海茫月
北海茫月 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:52

    Create a new Swift file copy this code, that's it call then drawPolygon() method from map view for polygon line.

    import GoogleMaps
    
    private struct MapPath : Decodable{
        var routes : [Route]?
    }
    
    private struct Route : Decodable{ 
        var overview_polyline : OverView?
    }
    
    private struct OverView : Decodable {
        var points : String?
    }
    
    extension GMSMapView {
    
        //MARK:- Call API for polygon points
    
        func drawPolygon(from source: CLLocationCoordinate2D, to destination: CLLocationCoordinate2D){
    
            let config = URLSessionConfiguration.default
            let session = URLSession(configuration: config)
    
            guard let url = URL(string: "https://maps.googleapis.com/maps/api/directions/json?origin=\(source.latitude),\(source.longitude)&destination=\(destination.latitude),\(destination.longitude)&sensor=false&mode=driving") else {
                return
            }
    
            DispatchQueue.main.async {
    
                session.dataTask(with: url) { (data, response, error) in
    
                    guard data != nil else {
                        return
                    }
                    do {
    
                        let route = try JSONDecoder().decode(MapPath.self, from: data!)
    
                        if let points = route.routes?.first?.overview_polyline?.points {
                            self.drawPath(with: points)
                        }
                        print(route.routes?.first?.overview_polyline?.points)
    
                    } catch let error {
    
                        print("Failed to draw ",error.localizedDescription)
                    }
                    }.resume()
                }
        }
    
        //MARK:- Draw polygon
    
        private func drawPath(with points : String){
    
            DispatchQueue.main.async {
    
                let path = GMSPath(fromEncodedPath: points)
                let polyline = GMSPolyline(path: path)
                polyline.strokeWidth = 3.0
                polyline.strokeColor = .red
                polyline.map = self
    
            }
        }
    }
    

提交回复
热议问题