class DirectionsService {
static const String _baseUrl =
'https://maps.googleapis.com/maps/api/directions/json';
static Future<DirectionsResult?> getDirections({
required String origin,
required String destination,
}) async {
final url = Uri.parse(
'$_baseUrl?origin=${Uri.encodeComponent(origin)}'
'&destination=${Uri.encodeComponent(destination)}'
'&mode=driving'
'&key=${ApiConfig.googleMapsApiKey}',
);
final response = await http.get(url);
if (response.statusCode != 200) {
return null;
}
final data = json.decode(response.body);
if (data['status'] != 'OK') {
return null;
}
final route = data['routes'][0];
final leg = route['legs'][0];
// Decode polyline
final polylinePoints =
_decodePolyline(route['overview_polyline']['points']);
// Extract bounds
final bounds = route['bounds'];
final northeast = LatLng(
bounds['northeast']['lat'].toDouble(),
bounds['northeast']['lng'].toDouble(),
);
final southwest = LatLng(
bounds['southwest']['lat'].toDouble(),
bounds['southwest']['lng'].toDouble(),
);
return DirectionsResult(
polylinePoints: polylinePoints,
distanceMeters: leg['distance']['value'],
distanceText: leg['distance']['text'],
durationSeconds: leg['duration']['value'],
durationText: leg['duration']['text'],
startLocation: LatLng(
leg['start_location']['lat'].toDouble(),
leg['start_location']['lng'].toDouble(),
),
endLocation: LatLng(
leg['end_location']['lat'].toDouble(),
leg['end_location']['lng'].toDouble(),
),
bounds: LatLngBounds(southwest: southwest, northeast: northeast),
);
}
}