NavigationStep.fromMapboxStep constructor

NavigationStep.fromMapboxStep(
  1. Map<String, dynamic> step
)

//////////// //////////// Creates a NavigationStep from Mapbox API response with robust error handling

Implementation

// III.C - Factory Methods
///////////////
/// Creates a NavigationStep from Mapbox API response with robust error handling
factory NavigationStep.fromMapboxStep(Map<String, dynamic> step) {
  try {
    // Safely extract maneuver data with null checks
    final maneuver = step['maneuver'] as Map<String, dynamic>? ?? {};

    // Safe location extraction with type conversion
    final locationData = maneuver['location'] as List? ?? [0.0, 0.0];

    return NavigationStep(
      // Provide default values with null coalescing
      instruction: (maneuver['instruction'] as String?) ??
                  (step['name'] != null ? 'Continue on ${step['name']}' : 'Continue'),
      location: RaliPosition(
        locationData.isNotEmpty ? (locationData[0] as num?)?.toDouble() ?? 0.0 : 0.0,
        locationData.length > 1 ? (locationData[1] as num?)?.toDouble() ?? 0.0 : 0.0
      ),
      // Safely convert numeric values
      distance: step['distance'] != null
        ? (step['distance'] as num).toDouble()
        : 0.0,
      duration: step['duration'] != null
        ? (step['duration'] as num).toDouble()
        : 0.0,
      maneuver: (maneuver['type'] as String?) ?? 'straight',
      roadName: step['name'] as String?,
      speedLimit: step['speedLimit'] != null
        ? (step['speedLimit'] as num).toDouble()
        : null,
      trafficStatus: step['congestion'] as String?,
      hazardWarning: step['warning'] as String?,
    );
  } catch (e) {
    print('Error parsing navigation step: $e');
    return NavigationStep(
      instruction: 'Continue',
      location: RaliPosition(0.0, 0.0),
      distance: 0.0,
      duration: 0.0,
      maneuver: 'straight',
    );
  }
}