从GMSMapView上的GMSPolyline中移除已经绘制的路径(Swift iOS)

3

我正在使用谷歌距离API["https://maps.googleapis.com/maps/api/directions/json?origin=" +start.latitude + "," + start.longitude +"&destination=" + end.latitude +"," + end.longitude + "&alternatives=false" +"&mode=driving&key=" + key;]来获取从起点到终点的路线。

我正在使用以下代码在起点和目的地之间绘制路线:

func drawPath()
{
    if polylines != nil {
        polylines?.map = nil
        polylines = nil
    }

    if animationPolyline != nil {
        self.animationIndex = 0
        self.animationPath = GMSMutablePath()
        self.animationPolyline.map = nil
        if self.timer != nil {
            self.timer.invalidate()
        }
    }


    setupStartRideLocationMarkup(CLLocationCoordinate2D(latitude: (currentLocation?.coordinate.latitude)!, longitude: (currentLocation?.coordinate.longitude)!))

    if currentLocation != nil && destinationLocation != nil {
        let origin = "\((currentLocation?.coordinate.latitude)!),\((currentLocation?.coordinate.longitude)!)"
        let destination = "\((destinationLocation?.latitude)!),\((destinationLocation?.longitude)!)"


        let url = "https://maps.googleapis.com/maps/api/directions/json?origin=\(origin)&destination=\(destination)&mode=driving&key=MY_API_KEY"

        Alamofire.request(url).responseJSON { response in


            let json = JSON(data: response.data!)
            self.jsonRoute = json
            let routes = json["routes"].arrayValue

            for route in routes
            {
                let routeOverviewPolyline = route["overview_polyline"].dictionary
                let points = routeOverviewPolyline?["points"]?.stringValue
                self.path = GMSPath.init(fromEncodedPath: points!)!
                self.polylines = GMSPolyline.init(path: self.path)
                self.polylines?.geodesic = true
                self.polylines?.strokeWidth = 5
                self.polylines?.strokeColor = UIColor.black
                self.polylines?.map = self.mapView
            }

            self.shouldDrawPathToStartLocation()
            self.shouldDrawPathToEndLocation()

            if routes.count > 0 {
                self.startAnimatingMap()
            }
        }
    }
}

正如您所看到的,我正在使用来自api的编码路径初始化路径。现在我想从整个路径中删除已经行驶过的GMSPolyline。我该怎么做?我的当前直觉是应该在didUpdateLocations方法中实现。以下是我的didUpdateLocations方法的代码:

 func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    currentLocation = locations.last!

    let camera = GMSCameraPosition.camera(withLatitude: (currentLocation?.coordinate.latitude)!,
                                          longitude: (currentLocation?.coordinate.longitude)!,
                                          zoom: zoomLevel)

    if (mapView?.isHidden)! {
        mapView?.isHidden = false
        mapView?.camera = camera
    } else {
        mapView?.animate(to: camera)
    }

    updatePolyLineIfRequired()

}

updatePolyLineIfRequired中,我想要移除已行驶的折线。

func updatePolyLineIfRequired(){
    if GMSGeometryIsLocationOnPath((currentLocation?.coordinate)!, path, true) {
        if startPolyline != nil {
            startPolyline?.map = nil
            startPolyline = nil
        }

    }
}

我希望实现类似于Uber或Careem的解决方案,其中绘制的GMSPolyline会被删除,直到用户当前位置。
提前感谢您。 附言:我正在使用Alamofire SwiftyJSON。
1个回答

2

针对此问题,有两种解决方案:

  1. 每次调用didUpdateLocations函数时调用Directions API。(效率不高)
  2. 从GMSPath中移除已行驶的坐标。

除非你的Direction API请求限制较少,否则调用Directions API将没有用处。

要删除路径中已行驶的坐标,请按以下步骤操作:

    //Call this function in didUpdateLocations
func updateTravelledPath(currentLoc: CLLocationCoordinate2D){
    var index = 0
    for i in 0..<self.path.count(){
        let pathLat = Double(self.path.coordinate(at: i).latitude).rounded(toPlaces: 3)
        let pathLong = Double(self.path.coordinate(at: i).longitude).rounded(toPlaces: 3)

        let currentLaenter code heret = Double(currentLoc.latitude).rounded(toPlaces: 3)
        let currentLong = Double(currentLoc.longitude).rounded(toPlaces: 3)

        if currentLat == pathLat && currentLong == pathLong{
            index = Int(i)
            break   //Breaking the loop when the index found
        }
    }

   //Creating new path from the current location to the destination
    let newPath = GMSMutablePath()    
    for i in index..<Int(self.path.count()){
        newPath.add(self.path.coordinate(at: UInt(i)))
    }
    self.path = newPath
    self.polyline.map = nil
    self.polyline = GMSPolyline(path: self.path)
    self.polyline.strokeColor = UIColor.darkGray
    self.polyline.strokeWidth = 2.0
    self.polyline.map = self.mapView
}

经纬度会被四舍五入,以便用户附近的旅行位置能够匹配。根据需要使用以下扩展程序将其舍入到3位或更多小数位。

extension Double {
// Rounds the double to decimal places value
func rounded(toPlaces places:Int) -> Double {
    let divisor = pow(10.0, Double(places))
    return (self * divisor).rounded() / divisor
}
}

如果用户从中途走了不同的路径,那么地图上绘制的路径将会失效。在这种情况下,我该如何获取新的路径? - Niraj

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接