Swift - Google Maps update directions from current

2019-07-28 21:04发布

问题:

I am currently in the process of learning the Google Maps API for Swift, and therefore I have a couple of questions that I hope can be answered by some of you guys. It just so happens that I am trying to create an app that simply gives the user directions, and much like Apple Maps and Google Maps, it simply draws a direction route for the user. I have managed to make this work, but what I am struggling with - is to simply 'update' the directions instead of constantly 'creating' new direction routes each time the location of the user updates. How would I proceed in order to do this?

This is a modified code that I found some other place here on stackOverflow that i am currently using to draw the direction:

 func drawPath(startLocation: CLLocation, endLocation: CLLocation)
    {
        let origin = "\(startLocation.coordinate.latitude),\(startLocation.coordinate.longitude)"
        let destination = "\(endLocation.coordinate.latitude),\(endLocation.coordinate.longitude)"


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

        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 = JSON(data: response.data!)
            let routes = json["routes"].arrayValue

            // print route using Polyline
            for route in routes
            {
                let routeOverviewPolyline = route["overview_polyline"].dictionary
                let points = routeOverviewPolyline?["points"]?.stringValue
                let path = GMSPath.init(fromEncodedPath: points!)
                let polyline = GMSPolyline.init(path: path)
                polyline.strokeWidth = 4
                polyline.strokeColor = UIColor.red
                polyline.map = self.mapView
            }

        }
    }

What I am struggling with however, is to make this 'active' - and update the direction according to the current location of the user. In other words, avoid having a marked distance 'behind' the user that is no longer necessary. Any ideas? And also, is it impossible to fetch information such as 'time to destination' and 'distance to destination' as well? Or is this something I have to do my providing a direct link to the Google Maps app?

Thanks in advance!