使用 Swift iOS,如何在 Google Maps 上规划两点之间的路线并添加多个途经点?

4

我有这段代码,但是由于某些原因它只绘制了两个点之间的路径(第一个和最后一个点),忽略了所有其他点(即[index == 1至index == n-1])

输出结果:仅在两个标记之间绘制路线

期望输出结果:在所有标记(5个标记)之间绘制路线

有人知道我的代码哪里出错了吗?

 func getDotsToDrawRoute(positions : [CLLocationCoordinate2D], completion: @escaping(_ path : GMSPath) -> Void) {
    if positions.count > 1 {
        let origin = positions.first
        let destination = positions.last
        var wayPoints = ""
        for point in positions {
            wayPoints = wayPoints.characters.count == 0 ? "\(point.latitude),\(point.longitude)" : "\(wayPoints)|\(point.latitude),\(point.longitude)"
        }
        print("this is fullPath :: \(wayPoints)")
        let request = "https://maps.googleapis.com/maps/api/directions/json"
        let parameters : [String : String] = ["origin" : "\(origin!.latitude),\(origin!.longitude)", "destination" : "\(destination!.latitude),\(destination!.longitude)", "wayPoints" : wayPoints, "stopover": "true", "key" : kyes.google_map]
        Alamofire.request(request, method:.get, parameters : parameters).responseJSON(completionHandler: { response in
            guard let dictionary = response.result.value as? [String : AnyObject]
                else {
                    return
            }
            print ("route iss ::: \(dictionary["routes"])")
            if let routes = dictionary["routes"] as? [[String : AnyObject]] {
                if routes.count > 0 {
                    var first = routes.first
                    if let legs = first!["legs"] as? [[String : AnyObject]] {
                        let fullPath : GMSMutablePath = GMSMutablePath()
                        for leg in legs {
                            if let steps = leg["steps"] as? [[String : AnyObject]] {
                                for step in steps {
                                    if let polyline = step["polyline"] as? [String : AnyObject] {
                                        if let points = polyline["points"] as? String {
                                            fullPath.appendPath(path: GMSMutablePath(fromEncodedPath: points))
                                        }
                                    }
                                }

                                let polyline = GMSPolyline.init(path: fullPath)

                                polyline.path = fullPath
                                polyline.strokeWidth = 4.0
                                polyline.map = self._map                                }
                        }
                    }
                }
            }
        })
    }
}

waypoint变量应该是一个字符串数组,其中每个字符串应该是由逗号分隔的位置的纬度和经度。 - Aravind Bhuvanendran
已经是这样了,这是准备好后的航点列表:24.7618090308257,46.605559787157|24.75161673279,46.6651155058871|24.7811909269468,46.6336618042914|24.7497328878959,46.6820742483448|24.7102263535113,46.6874250662913|24.7845409226333,46.6233112442547 @AravindBhuvanendran - Mesh
不要在alamofire中单独发送参数,你可以创建一个带有参数的URL,并像这样调用Get方法: https://maps.googleapis.com/maps/api/directions/json?origin=orglat, orglong&destination=destlat, destlong2&waypoints=waypointlat1, waypointlong1|waypointlat2, waypointlong2&mode=driving&key=GoogleKey - Aravind Bhuvanendran
我刚刚更新了你的URL并尝试了一下,结果是:“致命错误:'try!'表达式意外地引发了一个错误:Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.}:" @AravindBhuvanendran - Mesh
由于符号“|”而导致致命错误,因此我将其更改为“%7C”,但仍然没有任何积极的结果。@AravindBhuvanendran - Mesh
显示剩余2条评论
3个回答

6
请查看这个解决方案,对我而言运行良好。
    func drawpath(positions: [CLLocationCoordinate2D]) {

    let origin = positions.first!
    let destination = positions.last!
    var wayPoints = ""
    for point in positions {
        wayPoints = wayPoints.characters.count == 0 ? "\(point.latitude),\(point.longitude)" : "\(wayPoints)%7C\(point.latitude),\(point.longitude)"
    }

    let url = "https://maps.googleapis.com/maps/api/directions/json?origin=\(origin!.latitude),\(origin!.longitude)&destination=\(destination.latitude),\(destination.longitude)&mode=driving&waypoints=\(wayPoints)&key=KEY"
    Alamofire.request(url).responseJSON { response in

        print(response.request as Any)  // original URL request
        print(response.response as Any) // HTTP URL response
        print(response.data as Any)     // server data
        print(response.result as Any)   // result of response serialization

        let json = try!  JSON(data: response.data!)
        let routes = json["routes"][0]["overview_polyline"]["points"].stringValue

        let path = GMSPath.init(fromEncodedPath: routes)
        let polyline = GMSPolyline.init(path: path)
        polyline.strokeWidth = 4
        polyline.strokeColor = UIColor.red
        polyline.map = self._map
    }


}

0

尝试使用:

    func getPolylineRoute(from source: CLLocationCoordinate2D, to destination: CLLocationCoordinate2D){
        self.mapView.clear()
        let config = URLSessionConfiguration.default
        let session = URLSession(configuration: config)

        let url = URL(string: "https://maps.googleapis.com/maps/api/directions/json?origin=\(source.latitude),\(source.longitude)&destination=\(destination.latitude),\(destination.longitude)&sensor=true&mode=driving&key=YOUR_API_KEY")! 
        let task = session.dataTask(with: url, completionHandler: {
            (data, response, error) in
            if error != nil {
                print("Error" + error!.localizedDescription)
            }else {
                do {
                    if let json : [String:Any] = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]{
                        guard let routes = json["routes"] as? NSArray else {
                            return
                        }
                        print(routes)
                        if (routes.count > 0) {
                            let overview_polyline = routes[0] as? NSDictionary
                            let dictPolyline = overview_polyline?["overview_polyline"] as? NSDictionary
                            let points = dictPolyline?.object(forKey: "points") as? String
                            self.showPath(polyStr: points!)

                            let distancia = overview_polyline?["legs"] as? NSArray
                            let prueba = distancia![0] as? NSDictionary
                            let distancia2 = prueba?["distance"] as? NSDictionary
                            let control = distancia2?.object(forKey: "text") as! String

                            DispatchQueue.main.async {
                                let bounds = GMSCoordinateBounds(coordinate: source, coordinate: destination)
                                let update = GMSCameraUpdate.fit(bounds, with: UIEdgeInsetsMake(170, 30, 30, 30))
                                self.mapView!.moveCamera(update)
                            }
                        }
                    }
                }
                catch {
                    print("error in JSONSerialization")

                }
            }
        })
        task.resume()
    }

你使用方法调用

self.getPolylineRoute(from: origin, to: destination)

记得在 Google URL 中将 YOUR_API_KEY 替换为你的 API 密钥。


0

您可以使用此函数绘制覆盖您航点的折线。

请确保positions没有相同的航点坐标。如果有,它将只从源到目的地绘制折线

func drawPolyLine(for positions: [CLLocationCoordinate2D]) {
            let origin = positions.first!
            let destination = positions.last!
            var wayPoints = ""
            for point in positions {
                wayPoints = wayPoints.count == 0 ? "\(point.latitude),\(point.longitude)" : "\(wayPoints)%7C\(point.latitude),\(point.longitude)"
            }
            let url = "https://maps.googleapis.com/maps/api/directions/json?origin=\(origin.latitude),\(origin.longitude)&destination=\(destination.latitude),\(destination.longitude)&mode=driving&waypoints=\(wayPoints)&key=\(YOUR_GOOLE_MAP_API_KEY)"
            Alamofire.request(url).responseJSON { response in
                do {
                    let json = try JSONSerialization.jsonObject(with: response.data!, options: .allowFragments) as? [String: Any]
                    guard let routes = json?["routes"] as? NSArray else {
                        return
                    }
                    for route in routes {
                        let routeOverviewPolyline: NSDictionary = ((route as? NSDictionary)!.value(forKey: "overview_polyline") as? NSDictionary)!
                        let points = routeOverviewPolyline.object(forKey: "points")
                        let path = GMSPath.init(fromEncodedPath: (points! as? String)!)
                        let polyline = GMSPolyline.init(path: path)
                        polyline.strokeWidth = 4
                        polyline.strokeColor = UIColor(red: 95/255.0, green: 233/255.0, blue: 188/255.0, alpha: 1.0)
                        polyline.map = self.mapView
                    }
                } catch {
                    print("Unexpected Error")
                }
            }
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接