Parth Adroja
Parth Adroja

Reputation: 13524

Update polyline as user moves

I am using GoogleMaps to draw route. What I want to do is when user travels on that route remove the line which is already travelled(Like Uber does). I guess we can do it with removing the points from the polyline and redraw it. Is it the correct approach?

How can I know that those points are travelled and need to update the path?

Upvotes: 4

Views: 2391

Answers (1)

Bhavesh Odedara
Bhavesh Odedara

Reputation: 79

1) Create Globle Variable

var demoPolyline = GMSPolyline()
var demoPolylineOLD = GMSPolyline()
// Set Destination Location Cordinates
var destinationLocation = CLLocation(latitude: 23.072837, longitude: 72.516455)

2) Use CLLocationManagerDelegate Method For update current location

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

     let originalLoc: String = "\(location.coordinate.latitude),\(location.coordinate.longitude)"
     let destiantionLoc: String = "\(destinationLocation.coordinate.latitude),\(destinationLocation.coordinate.longitude)"

     let latitudeDiff: Double = Double(location.coordinate.latitude) - Double(destinationLocation.coordinate.latitude)
     let longitudeDiff: Double = Double(location.coordinate.longitude) - Double(destinationLocation.coordinate.longitude)

     let waypointLatitude = location.coordinate.latitude - latitudeDiff
     let waypointLongitude = location.coordinate.longitude - longitudeDiff

     getDirectionsChangedPolyLine(origin: originalLoc, destination: destiantionLoc, waypoints: ["\(waypointLatitude),\(waypointLongitude)"], travelMode: nil, completionHandler: nil)
}

3) Create Method For Draw and update Polyline on Google map

 func getDirectionsChangedPolyLine(origin: String!, destination: String!, waypoints: Array<String>!, travelMode: AnyObject!, completionHandler: ((_ status:   String, _ success: Bool) -> Void)?)
{

    DispatchQueue.main.asyncAfter(deadline: .now()) {

        if let originLocation = origin {
            if let destinationLocation = destination {
                var directionsURLString = "https://maps.googleapis.com/maps/api/directions/json?" + "origin=" + originLocation + "&destination=" + destinationLocation
                if let routeWaypoints = waypoints {
                    directionsURLString += "&waypoints=optimize:true"

                    for waypoint in routeWaypoints {
                        directionsURLString += "|" + waypoint
                    }
                }

                directionsURLString = directionsURLString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!

                let directionsURL = NSURL(string: directionsURLString)
                DispatchQueue.main.async( execute: { () -> Void in
                    let directionsData = NSData(contentsOf: directionsURL! as URL)
                    do{
                        let dictionary: Dictionary<String, AnyObject> = try JSONSerialization.jsonObject(with: directionsData! as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! Dictionary<String, AnyObject>

                        let status = dictionary["status"] as! String
                        if status == "OK" {

                            self.selectedRoute = (dictionary["routes"] as! Array<Dictionary<String, AnyObject>>)[0]
                            self.overviewPolyline = self.selectedRoute["overview_polyline"] as! Dictionary<String, AnyObject>

                            let route = self.overviewPolyline["points"] as! String
                            let path: GMSPath = GMSPath(fromEncodedPath: route)!

                            self.demoPolylineOLD = self.demoPolyline
                            self.demoPolylineOLD.strokeColor = UIColor.blue
                            self.demoPolylineOLD.strokeWidth = 3.0
                            self.demoPolylineOLD.map = self.mapView
                            self.demoPolyline.map = nil

                            self.demoPolyline = GMSPolyline(path: path)
                            self.demoPolyline.map = self.mapView
                            self.demoPolyline.strokeColor = UIColor.blue
                            self.demoPolyline.strokeWidth = 3.0
                            self.demoPolylineOLD.map = nil


                        } else {

                            self.getDirectionsChangedPolyLine(origin: origin, destination: destination, waypoints: waypoints, travelMode: travelMode, completionHandler: completionHandler)
                        }
                    } catch {

                        self.getDirectionsChangedPolyLine(origin: origin, destination: destination, waypoints: waypoints, travelMode: travelMode, completionHandler: completionHandler)
                    }
                })
            } else {

                print("Destination Location Not Found")
            }
        } else {

            print("Origin Location Not Found")
        }
    }
}

This is working on my live project

I hope this will work for everybody

Upvotes: 1

Related Questions