【问题标题】:SWIFT: google maps draw waypoint polylineSWIFT:谷歌地图绘制航路点折线
【发布时间】:2016-10-07 14:28:31
【问题描述】:

您好,我想知道是否有一种方法可以在 Google 地图 iOS 中的两个或多个标记之间绘制航点。我不想画直线……但只使用公共道路。这是我绘制直线的一些代码,但它不是我想要的。

    @objc private func makeGpsPath(){
    for i in 0 ..< trailArr.count {
        path.add(trailArr[i])
    }
    let polyline = GMSPolyline(path: path)
    polyline.strokeWidth = 5.0
    polyline.strokeColor = UIColor.black
    polyline.map = mapViewContainer
}

【问题讨论】:

    标签: swift google-maps


    【解决方案1】:

    要在两个或多个点之间绘制折线,您应该使用谷歌地图请求阅读此链接https://developers.google.com/maps/documentation/directions/intro#Waypoints 在我的情况下,我做到了

        func drawRoute() {
        ServerCommunicator.getDotsToDrawRoute(positions: positions, completion: { path in
            self.route.countRouteDistance(p: path)
            self.polyline.path = path
            self.polyline.strokeColor = UserSession.tintColor
            self.polyline.strokeWidth = 4.0
            self.polyline.map = self._mapView
        })
    }
    

    和请求的部分

    static 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)"
            }
            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, "key" : googleAPI_KEY]
            Alamofire.request(request, method:.get, parameters : parameters).responseJSON(completionHandler: { response in
                guard let dictionary = response.result.value as? [String : AnyObject]
                    else {
                        return
                }
                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(GMSMutablePath(fromEncodedPath: points))
                                            }
                                        }
                                    }
                                    completion(path: fullPath)
                                }
                            }
                        }
                    }
                }
            })
        }
    }
    extension GMSMutablePath {
    
    func appendPath(path : GMSPath?) {
        if let path = path {
            for i in 0..<path.count() {
                self.add(path.coordinate(at: i))
            }
        }
    }
    

    }

    【讨论】:

    • 收到此错误“GMSMutablePath”类型的值没有成员“appendPath”
    • 我编辑了答案,忘记添加我使用的扩展名
    • 什么是 self.add ?在那个扩展中。我尝试使用您更新的代码。现在我可以看到标记,但路径丢失了
    • 你的路径存在吗?要绘制它,您必须使用从 api 获得的带有路径的折线
    【解决方案2】:

    在 Swift 3 中在 GoogleMap 上的两个标记之间绘制折线。

    // Pass your source and destination coordinates in this method.
    func getPolylineRoute(from source: CLLocationCoordinate2D, to destination: CLLocationCoordinate2D){
    
            let config = URLSessionConfiguration.default
            let session = URLSession(configuration: config)
    
            let url = URL(string: "http://maps.googleapis.com/maps/api/directions/json?origin=\(source.latitude),\(source.longitude)&destination=\(destination.latitude),\(destination.longitude)&sensor=false&mode=driving")!
    
            let task = session.dataTask(with: url, completionHandler: {
                (data, response, error) in
                if error != nil {
                    print(error!.localizedDescription)
                }else{
                    do {
                        if let json : [String:Any] = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]{
    
                            let routes = json["routes"] as? [Any]
                            let overview_polyline = routes?[0] as?[String:Any]
                            let polyString = overview_polyline?["points"] as?String
    
                            //Call this method to draw path on map
                            self.showPath(polyStr: polyString!)
                        }
    
                    }catch{
                        print("error in JSONSerialization")
                    }
                }
            })
            task.resume()
        }
    

    在地图上绘制折线。

    func showPath(polyStr :String){
        let path = GMSPath(fromEncodedPath: polyStr)
        let polyline = GMSPolyline(path: path)
        polyline.strokeWidth = 3.0
        polyline.map = mapView // Your map view
    }
    

    【讨论】:

    • @VinothVino 你找到解决方案了吗?
    【解决方案3】:
    private func drowRoute(){
    
    let path = GMSMutablePath()
        path.addLatitude(self.lat!, longitude: self.long!)
        path.addLatitude(self.destLat!, longitude: self.destLong!)
    let polyline = GMSPolyline(path: path)
    polyline.strokeWidth = 2.0
    polyline.strokeColor = UIColor.blue
    polyline.geodesic = true
    polyline.map = mappView
    
    }
    

    【讨论】:

      【解决方案4】:
         let point3 = CLLocationCoordinate2D(latitude: Double(30.7173), longitude: Double(76.8329))
      
        let point4 = CLLocationCoordinate2D(latitude: Double(30.6942), longitude: Double(76.8606))
          let point5 = CLLocationCoordinate2D(latitude: Double(30.7465), longitude: Double(76.7872))
         var arrOfWayPoints : NSMutableArray = NSMutableArray()
                                          arrOfWayPoints.insert(point3, at: 0)
      
                                          arrOfWayPoints.insert(point4, at: 1)
      
                                          arrOfWayPoints.insert(point5, at: 2)
      
      
      
                                          self.drawRouteWithWaypoint(positions: arrOfWayPoints as! [CLLocationCoordinate2D])
      
       static var distance = Double()
      
      
          func drawRouteWithWaypoint(positions:[CLLocationCoordinate2D]) {
              LiveJob.getDotsToDrawRoute(positions: positions, completion: { path in
                  //self.route.countRouteDistance(p: path)
                  self.polyline.path = path
                  self.polyline.strokeColor = UIColor.blue
                  self.polyline.strokeWidth = 2.0
                  self.polyline.map = self.mapView
              })
      
              self.lblDistance.text = String(LiveJob.distance)
          }
      
          static 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)"
      
                  }
                  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,"mode" : "Transit","key" : "AIzaSyCtMHyxPEModWK8IgzBD96hQMFL-UCIjcY"]
                  Alamofire.request(request, method:.get, parameters : parameters).responseJSON(completionHandler: { response in
                      guard let dictionary = response.result.value as? [String : AnyObject]
                          else {
                              return
                      }
                      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 newLeg = legs[0]
                                  let distance = newLeg["distance"]
                                 // LiveJob.distance =  LiveJob.distance + distance!.doubleValue
      
      
      
                                  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))
                                                  }
                                              }
                                          }
                                          completion(fullPath)
                                      }
                                  }
                              }
                          }
                      }
                  })
              }
          }
      

      【讨论】:

        猜你喜欢
        • 2016-06-29
        • 1970-01-01
        • 2016-05-14
        • 1970-01-01
        • 2014-03-19
        • 2013-07-02
        • 2023-04-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多