Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for multiple/alternate routes, update dependencies #62

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion example/.flutter-plugins-dependencies
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"info":"This is a generated file; do not edit or check into version control.","plugins":{"ios":[{"name":"google_maps_flutter","path":"/Users/dammyololade/.pub-cache/hosted/pub.dartlang.org/google_maps_flutter-1.2.0/","dependencies":[]}],"android":[{"name":"flutter_plugin_android_lifecycle","path":"/Users/dammyololade/.pub-cache/hosted/pub.dartlang.org/flutter_plugin_android_lifecycle-1.0.11/","dependencies":[]},{"name":"google_maps_flutter","path":"/Users/dammyololade/.pub-cache/hosted/pub.dartlang.org/google_maps_flutter-1.2.0/","dependencies":["flutter_plugin_android_lifecycle"]}],"macos":[],"linux":[],"windows":[],"web":[]},"dependencyGraph":[{"name":"flutter_plugin_android_lifecycle","dependencies":[]},{"name":"google_maps_flutter","dependencies":["flutter_plugin_android_lifecycle"]}],"date_created":"2021-04-16 23:27:17.648271","version":"2.0.1"}
{"info":"This is a generated file; do not edit or check into version control.","plugins":{"ios":[{"name":"google_maps_flutter","path":"C:\\\\Users\\\\aaqib\\\\AppData\\\\Local\\\\Pub\\\\Cache\\\\hosted\\\\pub.dartlang.org\\\\google_maps_flutter-1.2.0\\\\","dependencies":[]}],"android":[{"name":"flutter_plugin_android_lifecycle","path":"C:\\\\Users\\\\aaqib\\\\AppData\\\\Local\\\\Pub\\\\Cache\\\\hosted\\\\pub.dartlang.org\\\\flutter_plugin_android_lifecycle-1.0.11\\\\","dependencies":[]},{"name":"google_maps_flutter","path":"C:\\\\Users\\\\aaqib\\\\AppData\\\\Local\\\\Pub\\\\Cache\\\\hosted\\\\pub.dartlang.org\\\\google_maps_flutter-1.2.0\\\\","dependencies":["flutter_plugin_android_lifecycle"]}],"macos":[],"linux":[],"windows":[],"web":[]},"dependencyGraph":[{"name":"flutter_plugin_android_lifecycle","dependencies":[]},{"name":"google_maps_flutter","dependencies":["flutter_plugin_android_lifecycle"]}],"date_created":"2021-07-01 12:41:50.745027","version":"2.3.0-24.1.pre"}
1 change: 1 addition & 0 deletions example/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
**/doc/api/
.dart_tool/
.flutter-plugins
.flutter-plugins-dependencies
.packages
.pub-cache/
.pub/
Expand Down
8 changes: 4 additions & 4 deletions example/ios/Flutter/flutter_export_environment.sh
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
#!/bin/sh
# This is a generated file; do not edit or check into version control.
export "FLUTTER_ROOT=/Users/dammyololade/fvm/versions/2.0.1"
export "FLUTTER_APPLICATION_PATH=/Users/dammyololade/StudioProjects/novu/flutter_polyline_points/example"
export "FLUTTER_TARGET=lib/main.dart"
export "FLUTTER_ROOT=C:\flutter"
export "FLUTTER_APPLICATION_PATH=D:\Programming\halal_hacks\flutter_polyline_points\example"
export "COCOAPODS_PARALLEL_CODE_SIGN=true"
export "FLUTTER_TARGET=lib\main.dart"
export "FLUTTER_BUILD_DIR=build"
export "SYMROOT=${SOURCE_ROOT}/../build/ios"
export "FLUTTER_BUILD_NAME=1.0.0"
export "FLUTTER_BUILD_NUMBER=1"
export "DART_OBFUSCATION=false"
Expand Down
8 changes: 4 additions & 4 deletions example/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -100,12 +100,12 @@ class _MapScreenState extends State<MapScreen> {
_getPolyline() async {
PolylineResult result = await polylinePoints.getRouteBetweenCoordinates(
googleAPiKey,
PointLatLng(_originLatitude, _originLongitude),
PointLatLng(_destLatitude, _destLongitude),
origin: PointLatLng(_originLatitude, _originLongitude),
destination: PointLatLng(_destLatitude, _destLongitude),
travelMode: TravelMode.driving,
wayPoints: [PolylineWayPoint(location: "Sabo, Yaba Lagos Nigeria")]);
if (result.points.isNotEmpty) {
result.points.forEach((PointLatLng point) {
if (result.routes[0].points.isNotEmpty) {
result.routes[0].points.forEach((PointLatLng point) {
polylineCoordinates.add(LatLng(point.latitude, point.longitude));
});
}
Expand Down
12 changes: 6 additions & 6 deletions example/pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ packages:
name: async
url: "https://pub.dartlang.org"
source: hosted
version: "2.5.0"
version: "2.7.0"
boolean_selector:
dependency: transitive
description:
Expand Down Expand Up @@ -75,7 +75,7 @@ packages:
path: ".."
relative: true
source: path
version: "0.2.6"
version: "1.0.1"
flutter_test:
dependency: "direct dev"
description: flutter
Expand All @@ -101,7 +101,7 @@ packages:
name: http
url: "https://pub.dartlang.org"
source: hosted
version: "0.13.1"
version: "0.13.3"
http_parser:
dependency: transitive
description:
Expand All @@ -122,7 +122,7 @@ packages:
name: meta
url: "https://pub.dartlang.org"
source: hosted
version: "1.3.0"
version: "1.4.0"
path:
dependency: transitive
description:
Expand Down Expand Up @@ -155,7 +155,7 @@ packages:
name: source_span
url: "https://pub.dartlang.org"
source: hosted
version: "1.8.0"
version: "1.8.1"
stack_trace:
dependency: transitive
description:
Expand Down Expand Up @@ -197,7 +197,7 @@ packages:
name: test_api
url: "https://pub.dartlang.org"
source: hosted
version: "0.2.19"
version: "0.4.0"
typed_data:
dependency: transitive
description:
Expand Down
65 changes: 48 additions & 17 deletions lib/flutter_polyline_points.dart
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ export 'src/utils/polyline_waypoint.dart';
export 'src/network_util.dart';
export 'src/PointLatLng.dart';
export 'src/utils/polyline_result.dart';
export 'src/utils/bounds.dart';
export 'src/utils/geocoded_waypoint.dart';
export 'src/utils/leg.dart';
export 'src/utils/route.dart';
export 'src/utils/status_code.dart';

class PolylinePoints {
NetworkUtil util = NetworkUtil();
Expand All @@ -19,23 +24,49 @@ class PolylinePoints {
/// which can be used to draw polyline between this two positions
///
Future<PolylineResult> getRouteBetweenCoordinates(
String googleApiKey, PointLatLng origin, PointLatLng destination,
{TravelMode travelMode = TravelMode.driving,
List<PolylineWayPoint> wayPoints = const [],
bool avoidHighways = false,
bool avoidTolls = false,
bool avoidFerries = true,
bool optimizeWaypoints = false}) async {
return await util.getRouteBetweenCoordinates(
googleApiKey,
origin,
destination,
travelMode,
wayPoints,
avoidHighways,
avoidTolls,
avoidFerries,
optimizeWaypoints);
String googleApiKey, {
PointLatLng? origin,
PointLatLng? destination,
String? originPlaceId,
String? destinationPlaceId,
TravelMode travelMode = TravelMode.driving,
List<PolylineWayPoint> wayPoints = const [],
bool avoidHighways = false,
bool avoidTolls = false,
bool avoidFerries = true,
bool optimizeWaypoints = false,
bool alternatives = false,
}) {
assert(
(origin != null || originPlaceId != null),
"origin or originPlaceId must be specified",
);
assert(
(destination != null || destinationPlaceId != null),
"destination or destinationPlaceId must be specified",
);
return util.getRouteBetweenCoordinates(
googleApiKey,
origin,
destination,
originPlaceId,
destinationPlaceId,
travelMode,
wayPoints,
avoidHighways,
avoidTolls,
avoidFerries,
optimizeWaypoints,
alternatives,
);
}

/// Decode the json body returned by the Directions API.
///
/// This is useful if you want to call the API on your own server
/// instead of on the client.
PolylineResult parseJson(dynamic json) {
return util.parseJson(json);
}

/// Decode and encoded google polyline
Expand Down
20 changes: 13 additions & 7 deletions lib/src/PointLatLng.dart
Original file line number Diff line number Diff line change
@@ -1,23 +1,29 @@


/// A pair of latitude and longitude coordinates, stored as degrees.
class PointLatLng {

/// Creates a geographical location specified in degrees [latitude] and
/// [longitude].
///
const PointLatLng(double latitude, double longitude)
: this.latitude = latitude,
this.longitude = longitude;
const PointLatLng(this.latitude, this.longitude);

/// The latitude in degrees.
final double latitude;

/// The longitude in degrees
final double longitude;

@override
bool operator ==(other) {
if (identical(this, other)) return true;
return (other is PointLatLng) &&
other.latitude == latitude &&
other.longitude == longitude;
}

@override
int get hashCode => latitude.hashCode ^ longitude.hashCode;

@override
String toString() {
return "lat: $latitude / longitude: $longitude";
}
}
}
130 changes: 99 additions & 31 deletions lib/src/network_util.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import 'dart:convert';

import 'package:flutter_polyline_points/src/utils/bounds.dart';
import 'package:flutter_polyline_points/src/utils/leg.dart';
import 'package:flutter_polyline_points/src/utils/route.dart';
import 'package:flutter_polyline_points/src/utils/status_code.dart';
import 'package:http/http.dart' as http;

import '../src/PointLatLng.dart';
Expand All @@ -8,56 +12,120 @@ import '../src/utils/request_enums.dart';
import 'utils/polyline_result.dart';

class NetworkUtil {
static const String STATUS_OK = "ok";

///Get the encoded string from google directions api
///
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}",
String googleApiKey,
PointLatLng? origin,
PointLatLng? destination,
String? originPlaceId,
String? destinationPlaceId,
TravelMode travelMode,
List<PolylineWayPoint> wayPoints,
bool avoidHighways,
bool avoidTolls,
bool avoidFerries,
bool optimizeWaypoints,
bool alternatives,
) async {

final mode = travelMode.toString().replaceAll('TravelMode.', '');
final result = PolylineResult();

final params = {
"mode": mode,
"avoidHighways": "$avoidHighways",
"avoidFerries": "$avoidFerries",
"avoidTolls": "$avoidTolls",
"alternatives": "$alternatives",
"key": googleApiKey
};

if (origin != null) {
params["origin"] = "${origin.latitude},${origin.longitude}";
} else {
params["origin"] = 'place_id:${originPlaceId!}';
}

if (destination != null) {
params["destination"] =
"${destination.latitude},${destination.longitude}";
} else {
params["destination"] = 'place_id:${destinationPlaceId!}';
}

if (wayPoints.isNotEmpty) {
List wayPointsArray = [];
wayPoints.forEach((point) => wayPointsArray.add(point.location));
final wayPointsArray = wayPoints.map((point) => point.location);
String wayPointsString = wayPointsArray.join('|');
if (optimizeWaypoints) {
wayPointsString = 'optimize:true|$wayPointsString';
}
params.addAll({"waypoints": wayPointsString});
params["waypoints"] = wayPointsString;
}
final avoidences = <String>[];
if (avoidHighways) avoidences.add("highways");
if (avoidTolls) avoidences.add("tolls");
if (avoidFerries) avoidences.add("ferries");
if (avoidences.isNotEmpty) params["avoid"] = avoidences.join('|');

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() == STATUS_OK &&
parsedJson["routes"] != null &&
parsedJson["routes"].isNotEmpty) {
result.points = decodeEncodedPolyline(
parsedJson["routes"][0]["overview_polyline"]["points"]);
} else {
result.errorMessage = parsedJson["error_message"];
return parseJson(parsedJson);
}
return result;
}

PolylineResult parseJson(dynamic parsedJson) {
final result = PolylineResult();
result.status = StatusCode(parsedJson["status"]);
if (result.status == StatusCode.OK &&
parsedJson["routes"] != null &&
parsedJson["routes"].isNotEmpty) {
final routes = <Route>[];

for (final route in parsedJson["routes"]) {
final bounds = Bounds(
PointLatLng(
route["bounds"]["northeast"]["lat"],
route["bounds"]["northeast"]["lng"],
),
PointLatLng(
route["bounds"]["southwest"]["lat"],
route["bounds"]["southwest"]["lng"],
),
);

final legs = <Leg>[];

for (final leg in route["legs"]) {
legs.add(Leg(
leg["distance"]["value"],
leg["distance"]["text"],
Duration(seconds: leg["duration"]["value"]),
leg["duration"]["text"],
leg["end_address"],
PointLatLng(
leg["end_location"]["lat"],
leg["end_location"]["lng"],
),
leg["start_address"],
PointLatLng(
leg["start_location"]["lat"],
leg["start_location"]["lng"],
),
));
}

final points = decodeEncodedPolyline(
route["overview_polyline"]["points"],
);

routes.add(Route(bounds, legs, points));
}
result.routes = routes;
} else {
result.errorMessage = parsedJson["error_message"];
}
return result;
}
Expand Down
Loading