【问题标题】:How to draw a polyline between multiple markers?如何在多个标记之间绘制折线?
【发布时间】:2018-08-04 08:48:59
【问题描述】:

想要从 userLocation 绘制一条折线到多个标记。在我的代码中已经在数组中添加了标记坐标,然后将 userLocation 添加到该数组的第 0 个位置。现在我想在数组元素之间绘制一条路线折线。我的代码如下...

self.coods.append(self.currentLocation)

                let jsonResponse = response.data
                do{

                    let json = try JSON(data: jsonResponse!)
                    self.dictXYZ = [json]
                    print("JsonResponse printed \(json["data"][0]["lattitude"])")
                    if let array = json["data"].array{
                        for i in 0..<array.count{
                        var coordinate = CLLocationCoordinate2D()
                            coordinate.latitude = array[i]["lattitude"].doubleValue
                            coordinate.longitude = array[i]["longitude"].doubleValue

                            self.coods.append(coordinate)
                        }

                        for j in self.coods {

                            let marker = GMSMarker()

                            marker.position = j
                            let camera = GMSCameraPosition.camera(withLatitude: j.latitude, longitude: j.longitude, zoom: 12)

                            self.mapView.camera = camera
                            marker.map = self.mapView
                        }

【问题讨论】:

    标签: ios swift xcode google-maps google-polyline


    【解决方案1】:
    let path = GMSMutablePath()
    for j in self.coods {
    path.add(j)
    }
    let polyline = GMSPolyline(path: path)
    polyline.map = mapView
    

    【讨论】:

    【解决方案2】:

    在 Google 开发者文档中。

    Waypoints - 指定一个中间位置数组,包括沿起点和目的地点之间的路线作为 途经或中途停留地点。航路点改变路线 引导它通过指定的位置。 API 支持 这些旅行模式的航路点:驾车、步行和骑自行车;不是 过境。

    首先,您需要为所有中间位置创建一个waypoints,以添加源和目标之间的路由。使用该折线,您可以创建 GMSPath,然后使用 GMSPolyline 绘制路线。我希望以下解决方案可以帮助您为多个位置绘制路线。

    func getPolylineRoute(from source: CLLocationCoordinate2D, to destinations: [CLLocationCoordinate2D], completionHandler: @escaping (Bool, String) -> ()) {
    
        guard let destination = destinations.last else {
            return
        }
        var wayPoints = ""
        for (index, point) in destinations.enumerated() {
            if index == 0 { // Skipping first location that is current location.
                continue.  
            }
            wayPoints = wayPoints.count == 0 ? "\(point.latitude),\(point.longitude)" : "\(wayPoints)%7C\(point.latitude),\(point.longitude)"
        }
    
        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&waypoints=\(wayPoints)&key=\(GOOGLE_API_KEY)")!
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            if error != nil {
                print("Failed : \(String(describing: error?.localizedDescription))")
                return
            } else {
                do {
                    if let json: [String: Any] = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any] {
                        guard let routes = json["routes"] as? [[String: Any]] else { return }
                        if (routes.count > 0) {
                            let overview_polyline = routes[0]
                            let dictPolyline = overview_polyline["overview_polyline"] as? NSDictionary
                            let points = dictPolyline?.object(forKey: "points") as? String
                            completionHandler(true, points!)
                        } else {
                            completionHandler(false, "")
                        }
                    }
                } catch {
                    print("Error : \(error)")
                }
            }
        }
        task.resume()
    }
    

    将当前位置和目标位置数组传递给getPolylineRoute 方法。然后用主线程中的折线点调用drawPolyline方法。

    getPolylineRoute(from: coods[0], to: coods) { (isSuccess, polylinePoints) in
        if isSuccess {
            DispatchQueue.main.async {
                self.drawPolyline(withMapView: self.mapView, withPolylinePoints: polylinePoints)
            }
        } else {
            print("Falied to draw polyline")
        }
    }
    
    func drawPolyline(withMapView googleMapView: GMSMapView, withPolylinePoints polylinePoints: String){
        path = GMSPath(fromEncodedPath: polylinePoints)!
        let polyline = GMSPolyline(path: path)
        polyline.strokeWidth = 3.0
        polyline.strokeColor = .lightGray
        polyline.map = googleMapView
    }
    

    【讨论】:

      【解决方案3】:

      首先创建 GMSPath 对象

      let path = GMSMutablePath()
      self.coods.forEach {
         path.add(coordinate: $0)
      }
      

      https://developers.google.com/maps/documentation/ios-sdk/reference/interface_g_m_s_mutable_path.html#af62038ea1a9da3faa7807b8d22e72ffb

      然后使用路径创建 GMSPolyline 对象

      let pathLine = GMSPolyline.with(path: path)
      pathLine.map = self.mapView
      

      https://developers.google.com/maps/documentation/ios-sdk/reference/interface_g_m_s_polyline.html#ace1dd6e6bab9295b3423712d2eed90a4

      【讨论】:

        猜你喜欢
        • 2018-03-08
        • 1970-01-01
        • 1970-01-01
        • 2021-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多