谷歌地图在2点之间的路线与多航点swift iOS

时间:2018-11-05 10:46:31

标签: ios google-maps swift3

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

输出:仅2个标记之间的路线

预期输出:所有标记(5个标记)之间的路线

是否有人知道我的代码有什么问题?

@Bean
@InboundChannelAdapter(channel = "fromSmartpath", poller = @Poller(cron = "0 15 8 ? * MON,TUE,WED,THU,FRI,SAT"))
public MessageSource<File> sftpMessageSource() throws SftpException {
    SftpInboundFileSynchronizingMessageSource source = new SftpInboundFileSynchronizingMessageSource(
            sftpInboundFileSynchronizer());
    source.setLocalDirectory(new File(Constants.LOCAL_REPOSITORY_PATH));
    source.setAutoCreateLocalDirectory(true);
    source.setLocalFilter(new FileSystemPersistentAcceptOnceFileListFilter(metaDataStore(), "metastore"));
    return source;
}

3 个答案:

答案 0 :(得分:3)

签出此解决方案,对我来说很好

    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
    }


}

答案 1 :(得分: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网址,将您的api密钥放在显示YOUR_API_KEY的位置

答案 2 :(得分: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")
                }
            }
        }