I write below code for removing the travelled path by a user but it will not worked as expected some time it will remove correctly and some time not. I observe one thing in this case after debugging a lot that is when we call direction API and getting route points for creating path then distance is always different between 2 successive points for example we have10 route coordinates between 2 points but all the coordinate have different distance from previous one.
func updateTravelledPath(currentLoc: CLLocationCoordinate2D){
var index = 0
if let counter = self.route?.path?.count() {
for i in 0..<counter {
let pathLat = Double(self.route?.path?.coordinate(at: i).latitude ?? 0.0).rounded(toPlaces: 5)
let pathLong = Double(self.route?.path?.coordinate(at: i).longitude ?? 0.0).rounded(toPlaces: 5)
let currentLat = Double(currentLoc.latitude).rounded(toPlaces: 5)
let currentLong = Double(currentLoc.longitude).rounded(toPlaces: 5)
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(counter){
if let cordd = self.route?.path?.coordinate(at: UInt(i)) {
newPath.add(cordd)
}
}
self.route?.path = newPath
DispatchQueue.main.async {
for item in self.route?.polyLine ?? [GMSPolyline]() {
item.map = nil
}
self.route?.polyLinee = nil
self.route?.polyLinee?.map = nil
self.route?.polyLinee = GMSPolyline(path: self.route?.path)
self.route?.polyLinee?.strokeWidth = 5.0
self.route?.polyLinee?.strokeColor = #colorLiteral(red: 0.02352941176, green: 0.5725490196, blue: 0.4666666667, alpha: 1)
self.route?.polyLine = [GMSPolyline(path: self.route?.path)]
self.route?.polyLinee?.map = self.mapView
self.mapView.reloadInputViews()
}
}
}
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
}
}
**Thanks in advance**