getDirections method
Fetch directions from origin to destination Returns list of LatLng points representing the route
Implementation
Future<List<Map<String, double>>> getDirections({
required double originLat,
required double originLng,
required double destLat,
required double destLng,
}) async {
final url = Uri.parse(
'https://api.olamaps.io/routing/v1/directions'
'?origin=$originLat,$originLng'
'&destination=$destLat,$destLng'
'&api_key=$apiKey',
);
try {
final response = await http.post(
url,
headers: {
'X-Request-Id': DateTime.now().millisecondsSinceEpoch.toString(),
},
);
if (response.statusCode == 200) {
final data = json.decode(response.body);
// Extract route coordinates from response
if (data['routes'] != null && (data['routes'] as List).isNotEmpty) {
final route = data['routes'][0];
final geometry = route['overview_polyline'];
if (geometry != null) {
// Decode polyline to get coordinates
return _decodePolyline(geometry);
}
}
// Fallback: return direct line if no geometry
return [
{'lat': originLat, 'lng': originLng},
{'lat': destLat, 'lng': destLng},
];
} else {
print('Routing API error: ${response.statusCode} - ${response.body}');
// Return direct line on error
return [
{'lat': originLat, 'lng': originLng},
{'lat': destLat, 'lng': destLng},
];
}
} catch (e) {
print('Error fetching directions: $e');
// Return direct line on error
return [
{'lat': originLat, 'lng': originLng},
{'lat': destLat, 'lng': destLng},
];
}
}