【问题标题】:google maps route between 2 points with multi waypoints swift ios谷歌地图 2 点之间的路线与多航点 swift ios
【发布时间】:2019-04-08 17:18:53
【问题描述】:

我有这段代码,但由于某种原因,它只是在 2 个点(第一个点和最后一个点)之间画了一个溃败,忽略了所有其他点,即 [index == 1 to index == n-1]

输出:仅在 2 个标记之间路由

预期输出:所有标记之间的路线(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 变量应该是一个字符串数组,其中每个字符串应该是位置的纬度经度,用逗号分隔。
  • 它已经这样,这里是航点的准备后的列表: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 SPAN >
  • 不是在alamofire中单独发送参数,你能不能用参数创建一个url,然后像这样调用Get方法maps.googleapis.com/maps/api/directions/json?origin=orglat, orglong&destination=destlat, destlong2&waypoints=waypointlat1, waypointlong1|waypointlat2, waypointlong2&mode=驾驶&key=GoogleKey
  • 我只是更新你的网址并尝试一下,结果是:“致命错误:'试试!'表达式意外引发错误:Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.}:" @AravindBhuvanendran
  • 你能把你的网址不带地图键吗?

标签: ios google-maps swift3


【解决方案1】:

看看这个解决方案是否适合我

    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
    }


}

【讨论】:

    【解决方案2】:

    尝试:

        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 中将您的 api 密钥放在显示 YOUR_API_KEY 的位置

    【讨论】:

      【解决方案3】:

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

      确保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")
                      }
                  }
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-27
        • 2018-05-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多