55 lines
1.6 KiB
Dart
55 lines
1.6 KiB
Dart
import 'dart:convert';
|
|
|
|
import 'package:http/http.dart' as http;
|
|
import 'package:latlong2/latlong.dart';
|
|
|
|
class OsrmRoutingService {
|
|
const OsrmRoutingService({
|
|
this.baseUrl = 'https://router.project-osrm.org',
|
|
this.profile = 'driving',
|
|
});
|
|
|
|
final String baseUrl;
|
|
final String profile;
|
|
|
|
Future<List<LatLng>> fetchRoute(List<LatLng> waypoints) async {
|
|
if (waypoints.length < 2) {
|
|
return <LatLng>[];
|
|
}
|
|
|
|
final coordinates = waypoints
|
|
.map((point) => '${point.longitude},${point.latitude}')
|
|
.join(';');
|
|
final uri = Uri.parse(
|
|
'$baseUrl/route/v1/$profile/$coordinates'
|
|
'?overview=full&geometries=geojson',
|
|
);
|
|
|
|
final response = await http.get(uri);
|
|
if (response.statusCode != 200) {
|
|
throw Exception('Routing request failed (${response.statusCode})');
|
|
}
|
|
|
|
final payload = jsonDecode(response.body) as Map<String, dynamic>;
|
|
final routes = payload['routes'];
|
|
if (routes is! List || routes.isEmpty) {
|
|
throw Exception('No route returned');
|
|
}
|
|
|
|
final geometry = routes.first['geometry'] as Map<String, dynamic>?;
|
|
final coordinatesList = geometry?['coordinates'];
|
|
if (coordinatesList is! List || coordinatesList.isEmpty) {
|
|
throw Exception('Route geometry missing');
|
|
}
|
|
|
|
return coordinatesList.map((pair) {
|
|
if (pair is! List || pair.length < 2) {
|
|
throw Exception('Invalid coordinate pair in route geometry');
|
|
}
|
|
final lon = (pair[0] as num).toDouble();
|
|
final lat = (pair[1] as num).toDouble();
|
|
return LatLng(lat, lon);
|
|
}).toList();
|
|
}
|
|
}
|