addDeviation method
Adds a deviation to the route at the specified index with the given parameters. Returns a Future
Implementation
Future<bool> addDeviation({
required int deviationPointIndex,
required double deviationLength,
required double deviationDistance,
required double skipDistance,
}) async {
// Validate input parameters
if (deviationPointIndex < 0 ||
deviationPointIndex >= _currentRoute.value.length - 1) {
throw RangeError('Deviation point index out of bounds');
}
if (deviationLength <= 0 || deviationDistance <= 0 || skipDistance <= 0) {
throw ArgumentError('Deviation parameters must be positive values');
}
// Find the starting point of the deviation
final startPoint = _currentRoute.value[deviationPointIndex];
// Find the approximate reconnection point based on skipDistance
int reconnectionIndex = deviationPointIndex;
double accumulatedDistance = 0.0;
while (reconnectionIndex < _currentRoute.value.length - 1 &&
accumulatedDistance < skipDistance) {
accumulatedDistance += _currentRoute.value[reconnectionIndex]
.distanceTo(_currentRoute.value[reconnectionIndex + 1]);
reconnectionIndex++;
}
if (reconnectionIndex >= _currentRoute.value.length - 1) {
reconnectionIndex = _currentRoute.value.length - 1;
}
final reconnectionPoint = _currentRoute.value[reconnectionIndex];
// Calculate a deviation path using OSRM
try {
final deviationPath = await _calculateDeviationPath(
startPoint: startPoint,
endPoint: reconnectionPoint,
deviationDistance: deviationDistance,
deviationLength: deviationLength,
);
if (deviationPath.isEmpty) {
return false;
}
// Apply the deviation to the current route
_currentRoute.value = [
..._currentRoute.value.sublist(0, deviationPointIndex),
...deviationPath,
..._currentRoute.value.sublist(reconnectionIndex + 1),
];
// Record the applied deviation
_appliedDeviations.value.add({
'deviationPointIndex': deviationPointIndex,
'deviationLength': deviationLength,
'deviationDistance': deviationDistance,
'skipDistance': skipDistance,
'appliedAt': DateTime.now().toIso8601String(),
});
return true;
} catch (e) {
debugPrint('Failed to add deviation: $e');
return false;
}
}