I want to have smoother polylines displayed on the map. See the screenshot of sharp polyline.
I found that "polylineQuality":"HIGH_QUALITY" is available in Routes Preferred API but not in Google Directions API I guess. Any ideas how to improve the polyline smoothness?
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:google_maps_flutter/google_maps_flutter.dart';
class Routing {
Future<List<LatLng>> getPolylinePoints(
LatLng source, LatLng destination) async {
String apiKey = "API_KEY";
String polylineQuality = "HIGH_QUALITY";
String baseUrl = "https://maps.googleapis.com/maps/api/directions/json?";
String url = "$baseUrl"
"origin=${source.latitude},${source.longitude}&"
"destination=${destination.latitude},${destination.longitude}&"
"key=$apiKey&"
"polylineQuality=$polylineQuality";
var response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
var jsonData = jsonDecode(response.body);
var points = jsonData['routes'][0]['overview_polyline']['points'];
return decodePolyline(points);
} else {
throw Exception("Failed to load directions");
}
}
List<LatLng> decodePolyline(String polyline) {
List<LatLng> points = [];
int index = 0;
int len = polyline.length;
int lat = 0;
int lng = 0;
while (index < len) {
int b;
int shift = 0;
int result = 0;
do {
b = polyline.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 = polyline.codeUnitAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = LatLng((lat / 1E5).toDouble(), (lng / 1E5).toDouble());
points.add(p);
}
return points;
}
}
Use Routes API instead of the Directions API
The documentation for Routes API states why you should migrate to Routes API. And it says that,
I'm assuming that you needed the
polylineQualityfor the Directions API because Routes preferred is only available to select customers and you need to Contact Sales to avail the feature you wanted.But if you take a look at Routes API, it actually has the same
polylineQualityfield where you can specify the quality of the poyline asHIGH_QUALITYorOVERVIEW. Ref: https://developers.google.com/maps/documentation/routes/config_trade_offs#example_setting_polyline_qualityYou can use this field when using
computeRoutesmethod of the Routes API. You can check out the reference documentation here: https://developers.google.com/maps/documentation/routes/reference/rest/v2/TopLevel/computeRoutes#polylinequalityHere's a guide from the documentation on how to Get a Route using
computeRoutes: https://developers.google.com/maps/documentation/routes/compute_route_directionsWith this, I think the Routes API should suffice with your use case.