如何在多个标记之间绘制PolyLine?

时间:2018-08-04 08:48:59

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

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

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
                        }

3 个答案:

答案 0 :(得分:1)

let path = GMSMutablePath()
for j in self.coods {
path.add(j)
}
let polyline = GMSPolyline(path: path)
polyline.map = mapView

答案 1 :(得分:0)

首先创建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

答案 2 :(得分:0)

在Google Developer Docs中。

  

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
}