getRouteBetweenCoordinates method

Future<PolylineResult> getRouteBetweenCoordinates(
  1. String googleApiKey,
  2. PointLatLng origin,
  3. PointLatLng destination,
  4. TravelMode travelMode,
  5. List<PolylineWayPoint> wayPoints,
  6. bool avoidHighways,
  7. bool avoidTolls,
  8. bool avoidFerries,
  9. bool optimizeWaypoints,
)

Get the encoded string from google directions api

Implementation

Future<PolylineResult> getRouteBetweenCoordinates(
    String googleApiKey,
    PointLatLng origin,
    PointLatLng destination,
    TravelMode travelMode,
    List<PolylineWayPoint> wayPoints,
    bool avoidHighways,
    bool avoidTolls,
    bool avoidFerries,
    bool optimizeWaypoints) async {
  String mode = travelMode.toString().replaceAll('TravelMode.', '');
  PolylineResult result = PolylineResult();
  var params = {
    "origin": "${origin.latitude},${origin.longitude}",
    "destination": "${destination.latitude},${destination.longitude}",
    "mode": mode,
    "avoidHighways": "$avoidHighways",
    "avoidFerries": "$avoidFerries",
    "avoidTolls": "$avoidTolls",
    "key": googleApiKey
  };
  if (wayPoints.isNotEmpty) {
    List wayPointsArray = [];
    for (var point in wayPoints) {
      wayPointsArray.add(point.location);
    }
    String wayPointsString = wayPointsArray.join('|');
    if (optimizeWaypoints) {
      wayPointsString = 'optimize:true|$wayPointsString';
    }
    params.addAll({"waypoints": wayPointsString});
  }
  Uri uri =
      Uri.https("maps.googleapis.com", "maps/api/directions/json", params);

  // print('GOOGLE MAPS URL: ' + url);
  var response = await http.get(uri);
  if (response.statusCode == 200) {
    var parsedJson = json.decode(response.body);
    result.status = parsedJson["status"];
    if (parsedJson["status"]?.toLowerCase() == statusOk &&
        parsedJson["routes"] != null &&
        parsedJson["routes"].isNotEmpty) {
      result.points = decodeEncodedPolyline(
          parsedJson["routes"][0]["overview_polyline"]["points"]);
    } else {
      result.errorMessage = parsedJson["error_message"];
    }
  }
  return result;
}