如何使用Google API和Swift在GMSmap视图Swift上绘制路线(非直线)

zysjyyx4  于 2023-10-15  发布在  Swift
关注(0)|答案(2)|浏览(142)

我正在尝试使用谷歌方向API在mapview上绘制路线。我使用的解决方案从堆栈溢出本身,但我得到了一些关于初始化错误。
方向路线将是相同的谷歌Map本身或直线之一?
我应该在哪里调用这些方法呢?
我得到的错误是:
无法使用类型为“(coordinate:字符串,字符串,坐标:字符串,字符串)'
下面是代码:

func getRouteSteps(from source: CLLocationCoordinate2D, to destination: CLLocationCoordinate2D) {
        
        let session = URLSession.shared
        
        let url = URL(string: "https://maps.googleapis.com/maps/api/directions/json?origin=\(lat),\(long)&destination=\(directionlat),\(directionlong)&sensor=false&mode=driving&key=\(API KEY)")!
        
        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] else {
                
                print("error in JSONSerialization")
                return
                
            }
            
            
            
            guard let routes = jsonResult!["routes"] as? [Any] else {
                return
            }
            
            guard let route = routes[0] as? [String: Any] else {
                return
            }
            
            guard let legs = route["legs"] as? [Any] else {
                return
            }
            
            guard let leg = legs[0] as? [String: Any] else {
                return
            }
            
            guard let steps = leg["steps"] as? [Any] else {
                return
            }
            for item in steps {
                
                guard let step = item as? [String: Any] else {
                    return
                }
                
                guard let polyline = step["polyline"] as? [String: Any] else {
                    return
                }
                
                guard let polyLineString = polyline["points"] as? String else {
                    return
                }
                
                //Call this method to draw path on map
                DispatchQueue.main.async {
                    self.drawPath(from: polyLineString)
                }
                
            }
        })
        task.resume()
    }

函数来绘制图形:

func drawPath(from polyStr: String){
        let mapView: GMSMapView
        let path = GMSPath(fromEncodedPath: polyStr)
        let polyline = GMSPolyline(path: path)
        polyline.strokeWidth = 3.0
        polyline.map = mapView // Google MapView
        
//
        let cameraUpdate = GMSCameraUpdate.fit(GMSCoordinateBounds(coordinate: "\(lat)","\(long)", coordinate: "\(directionlat)","\(directionlong)")) as? [String : AnyObject]
        mapView.moveCamera(cameraUpdate)
        let currentZoom = mapView.camera.zoom
        mapView.animate(toZoom: currentZoom - 1.4)
    }
iqih9akk

iqih9akk1#

GMSCoordinatesBoundsCLLocationCoordinates2D类型作为参数,而不是String
取代

let cameraUpdate = GMSCameraUpdate.fit(GMSCoordinateBounds(coordinate: "\(lat)","\(long)", coordinate: "\(directionlat)","\(directionlong)")) as? [String : AnyObject]

let cameraUpdate = GMSCameraUpdate.fit(GMSCoordinateBounds(coordinate: CLLocationCoordinate2D(latitude: Double(lat), longitude: Double(long)), coordinate: CLLocationCoordinate2D(latitude: Double(directionlat), longitude: Double(directionlat))))

一旦你把mapView添加到你的视图控制器中并得到坐标,调用你的函数

self.getRouteSteps(from source: CLLocationCoordinate2D(latitude: Double(lat), longitude: Double(long)), destination: CLLocationCoordinate2D(latitude: Double(directionlat), longitude: Double(directionlat)))
4xrmg8kj

4xrmg8kj2#

你可以试试这个,用下面的方法来获取方向:

//This function is used to fetch the directions from origin to destination

private func fetchDirection(destinationLat: CLLocationDegrees, destinationLong: CLLocationDegrees) {

    //Here you need to set your origin and destination points and mode

    if let location = locationManager.location {

            guard let url = URL(string: "\("https://maps.googleapis.com/maps/api/directions/json")?origin=\(location.coordinate.latitude),\(location.coordinate.longitude)&destination=\(destinationLat),\(destinationLong)&key=\(Constants.MapKey)") else { return }

            let task = URLSession.shared.dataTask(with: url) { [unowned self](data, response, error) -> Void in

                do {

                    guard let data = data else { return }

                    let decoder = JSONDecoder()

                    decoder.keyDecodingStrategy = .convertFromSnakeCase

                    guard let mapData = try? decoder.decode(MapModel.self, from: data) else { return }

                    if let points = mapData.routes.first?.overviewPolyline.points {

                        self.drawRoute(points: points)

                    }
                }

            }

            task.resume()

    }
}

使用此选项在Map上绘制路线:

//This function is used to draw the routes

private func drawRoute(points: String) {

        let path = GMSPath.init(fromEncodedPath: points)
        let singleLine = GMSPolyline.init(path: path)
        self.polylines.append(singleLine)
        singleLine.strokeWidth = 6.0
        let gradientColor: GMSStrokeStyle = GMSStrokeStyle.gradient(from: .red, to: .blue)
        singleLine.spans = [GMSStyleSpan.init(style: gradientColor)]

        if  self.polylines.count > 0 {

            self.polylines.forEach{ $0.map = nil }

        }

        singleLine.map = self.mapView

}

这是MapModel

struct MapModel: Decodable {

let status: String
let routes: [Routes]
}

struct Routes: Decodable {

let overviewPolyline: OverviewPolyline
}

struct OverviewPolyline: Decodable {

let points: String
}

我希望你熟悉Codables,而且,当我收到点时,我已经调用了drawRoute函数。

相关问题