首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用在GMSmap视图上快速(不直接)绘制路线

如何使用在GMSmap视图上快速(不直接)绘制路线
EN

Stack Overflow用户
提问于 2020-02-10 06:04:15
回答 2查看 297关注 0票数 1

我试图使用谷歌方向API在地图视图上绘制路线。我正在使用来自堆栈溢出本身的解决方案,但是我得到了一些关于intializers的错误。方向路线也会和谷歌地图本身一样,或者是笔直的路线。任何帮助都是非常感谢的。,我应该把这个方法称为,我得到的错误是

不能使用类型的参数列表(坐标:字符串、字符串、坐标: String、String )“”调用“GMSCoordinateBounds”类型的初始化程序

以下是守则。

代码语言:javascript
运行
复制
 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()
    } 

绘制折线函数

代码语言:javascript
运行
复制
 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)
    }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-02-10 06:13:29

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

替换

代码语言:javascript
运行
复制
let cameraUpdate = GMSCameraUpdate.fit(GMSCoordinateBounds(coordinate: "\(lat)","\(long)", coordinate: "\(directionlat)","\(directionlong)")) as? [String : AnyObject]

使用

代码语言:javascript
运行
复制
let cameraUpdate = GMSCameraUpdate.fit(GMSCoordinateBounds(coordinate: CLLocationCoordinate2D(latitude: Double(lat), longitude: Double(long)), coordinate: CLLocationCoordinate2D(latitude: Double(directionlat), longitude: Double(directionlat))))

将mapView添加到视图控制器并获得坐标后,调用您的函数

代码语言:javascript
运行
复制
self.getRouteSteps(from source: CLLocationCoordinate2D(latitude: Double(lat), longitude: Double(long)), destination: CLLocationCoordinate2D(latitude: Double(directionlat), longitude: Double(directionlat)))
票数 2
EN

Stack Overflow用户

发布于 2020-02-10 06:53:13

您可以尝试这样做,使用下面的方法获取方向:

代码语言:javascript
运行
复制
  //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()

    }
}

用它在地图上画出路线:

代码语言:javascript
运行
复制
    //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

代码语言:javascript
运行
复制
struct MapModel: Decodable {

let status: String
let routes: [Routes]
}

struct Routes: Decodable {

let overviewPolyline: OverviewPolyline
}

struct OverviewPolyline: Decodable {

let points: String
}

我希望您熟悉Codables,并且在收到这些要点时,我已经调用了drawRoute函数。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60144849

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档