82 lines
2.4 KiB
Dart
82 lines
2.4 KiB
Dart
import 'dart:convert';
|
|
import 'dart:io';
|
|
|
|
void main() async {
|
|
final envFile = File('functions/.env');
|
|
final lines = await envFile.readAsLines();
|
|
String apiKey = '';
|
|
for (var line in lines) {
|
|
if (line.startsWith('API_MAPS=')) {
|
|
apiKey = line.split('=')[1].replaceAll('"', '');
|
|
}
|
|
}
|
|
|
|
final url = 'https://routes.googleapis.com/directions/v2:computeRoutes';
|
|
final client = HttpClient();
|
|
|
|
final request = await client.postUrl(Uri.parse(url));
|
|
request.headers.set('Content-Type', 'application/json');
|
|
request.headers.set('X-Goog-Api-Key', apiKey);
|
|
request.headers.set('X-Goog-FieldMask', 'routes.distanceMeters,routes.duration,routes.polyline.encodedPolyline');
|
|
|
|
final payload = jsonEncode({
|
|
"travelMode": "DRIVE",
|
|
"routingPreference": "TRAFFIC_AWARE",
|
|
"routeModifiers": { "avoidTolls": true },
|
|
"origin": { "address": "401 route du camping, 69850 Saint Martin en haut" },
|
|
"destination": { "address": "25 Imp. du Puits du Suc, Saint-Martin-en-Haut, France" }
|
|
});
|
|
|
|
request.write(payload);
|
|
final response = await request.close();
|
|
final responseBody = await response.transform(utf8.decoder).join();
|
|
|
|
try {
|
|
final json = jsonDecode(responseBody);
|
|
final routes = json['routes'] as List;
|
|
final polyStr = routes[0]['polyline']['encodedPolyline'] as String;
|
|
|
|
print("Polyline found. Length: ${polyStr.length}");
|
|
print("String: $polyStr");
|
|
|
|
int index = 0, len = polyStr.length;
|
|
int lat = 0, lng = 0;
|
|
List poly = [];
|
|
while (index < len) {
|
|
int b, shift = 0, result = 0;
|
|
do {
|
|
b = polyStr.codeUnitAt(index++) - 63;
|
|
result |= (b & 0x1f) << shift;
|
|
shift += 5;
|
|
} while (b >= 0x20);
|
|
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
|
|
lat += dlat;
|
|
|
|
shift = 0;
|
|
result = 0;
|
|
do {
|
|
b = polyStr.codeUnitAt(index++) - 63;
|
|
result |= (b & 0x1f) << shift;
|
|
shift += 5;
|
|
} while (b >= 0x20);
|
|
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
|
|
lng += dlng;
|
|
|
|
double finalLat = lat / 1e5;
|
|
double finalLng = lng / 1e5;
|
|
|
|
if (finalLat.abs() > 90.0 || finalLng.abs() > 180.0) {
|
|
print("EXPLODED at index $index: $finalLat, $finalLng");
|
|
break;
|
|
}
|
|
poly.add([finalLat, finalLng]);
|
|
}
|
|
print("Decode complete. Points:");
|
|
for (var pt in poly) {
|
|
print(pt);
|
|
}
|
|
} catch (e) {
|
|
print("Error: $e");
|
|
}
|
|
}
|