Calculate Route¶
Setup¶
Prerequisites¶
Build and Run¶
Navigate to the route_calculation
directory within the Flutter examples directory. This is the project folder for this example.
Note - the gem_kit
directory containing the Maps SDK for Flutter
should be in the plugins
directory of the example, e.g.
example_pathname/plugins/gem_kit
- see the environment setup guide above.
Replace example_pathname
with the actual example path name,
such as address_search
Download project dependencies:
flutter upgrade
run the following terminal commands in the project directory,
where the pubspec.yaml
file is located:
flutter clean
flutter pub get
Run the example:
First, verify that the ANDROID_SDK_ROOT
environment variable
is set to the root path of your android SDK.
In android/build.gradle
add the maven {}
block as shown,
within the allprojects {} block
, for both debug and release builds,
without the line numbers, those are for reference:
1allprojects {
2 repositories {
3 google()
4 mavenCentral()
5 maven {
6 url "${rootDir}/../plugins/gem_kit/android/build"
7 }
8 }
9}
in android/app/build.gradle
within the android {}
block, in the defaultConfig {}
block,
the android SDK version minSdk
must be set as shown below.
Additionally, for release builds, in android/app/build.gradle
,
within the android {}
block, add the buildTypes {}
block as shown:
Replace example_pathname
with the actual example pathname, such as center_coordinates
1android {
2 defaultConfig {
3 applicationId "com.magiclane.gem_kit.examples.example_pathname"
4 minSdk 21
5 targetSdk flutter.targetSdk
6 versionCode flutterVersionCode.toInteger()
7 versionName flutterVersionName
8 }
9 buildTypes {
10 release {
11 minifyEnabled false
12 shrinkResources false
13
14 // TODO: Add your own signing config for the release build.
15 // Signing with the debug keys for now, so `flutter run --release` works.
16 signingConfig signingConfigs.debug
17 }
18 }
19}
Then run the project:
flutter run --debug
flutter run --release
In the ios/Podfile
configuration text file, at the top, set the minimum ios
platform to 13 like this:
platform :ios, '13.0'
Then run the project:
flutter run --debug
flutter run --release
How It Works¶
The example app demonstrates the following features:
Calculate a route between two landmarks.
Display the route on a map and allow user interaction with the route.
Provide options to cancel route calculation or clear the routes from the map.
1import 'package:gem_kit/core.dart';
2import 'package:gem_kit/map.dart';
3import 'package:gem_kit/routing.dart';
4
5import 'package:flutter/material.dart' hide Route;
6
7Future<void> main() async {
8 const projectApiToken = String.fromEnvironment('GEM_TOKEN');
9
10 await GemKit.initialize(appAuthorization: projectApiToken);
11
12 runApp(const MyApp());
13}
This imports the necessary packages, initializes GemKit, and sets up the main entry point of the app.
UI and Map Integration¶
1class MyApp extends StatelessWidget {
2 const MyApp({super.key});
3
4 @override
5 Widget build(BuildContext context) {
6 return const MaterialApp(
7 debugShowCheckedModeBanner: false,
8 title: 'Calculate Route',
9 home: MyHomePage(),
10 );
11 }
12}
13
14class MyHomePage extends StatefulWidget {
15 const MyHomePage({super.key});
16
17 @override
18 State<MyHomePage> createState() => _MyHomePageState();
19}
20
21class _MyHomePageState extends State<MyHomePage> {
22 late GemMapController _mapController;
23
24 TaskHandler? _routingHandler;
25 List<Route>? _routes;
26
27 @override
28 void dispose() {
29 GemKit.release();
30 super.dispose();
31 }
32
33 @override
34 Widget build(BuildContext context) {
35 return Scaffold(
36 appBar: AppBar(
37 backgroundColor: Colors.deepPurple[900],
38 title: const Text('Calculate Route',
39 style: TextStyle(color: Colors.white)),
40 actions: [
41 // Routes are not built.
42 if (_routingHandler == null && _routes == null)
43 IconButton(
44 onPressed: () => _onBuildRouteButtonPressed(context),
45 icon: const Icon(
46 Icons.route,
47 color: Colors.white,
48 ),
49 ),
50 // Routes calculating is in progress.
51 if (_routingHandler != null)
52 IconButton(
53 onPressed: () => _onCancelRouteButtonPressed(),
54 icon: const Icon(
55 Icons.stop,
56 color: Colors.white,
57 ),
58 ),
59 // Routes calculating is finished.
60 if (_routes != null)
61 IconButton(
62 onPressed: () => _onClearRoutesButtonPressed(),
63 icon: const Icon(
64 Icons.clear,
65 color: Colors.white,
66 ),
67 ),
68 ],
69 ),
70 body: GemMap(
71 onMapCreated: _onMapCreated,
72 ),
73 );
74 }
This code sets up the basic structure of the app, including the map and the app bar. It also provides buttons in the app bar for building, canceling, and clearing routes.
Route Calculation and Map Interaction¶
1// The callback for when map is ready to use.
2void _onMapCreated(GemMapController controller) {
3 // Save controller for further usage.
4 _mapController = controller;
5
6 // Register route tap gesture callback.
7 _registerRouteTapCallback();
8}
9
10void _onBuildRouteButtonPressed(BuildContext context) {
11 // Define the departure.
12 final departureLandmark =
13 Landmark.withLatLng(latitude: 48.85682, longitude: 2.34375);
14
15 // Define the destination.
16 final destinationLandmark =
17 Landmark.withLatLng(latitude: 50.84644, longitude: 4.34587);
18
19 // Define the route preferences.
20 final routePreferences = RoutePreferences();
21
22 _showSnackBar(context, message: "The route is being calculated.");
23
24 // Calling the calculateRoute SDK method.
25 // (err, results) - is a callback function that gets called when the route computing is finished.
26 // err is an error enum, results is a list of routes.
27
28 _routingHandler = RoutingService.calculateRoute(
29 [departureLandmark, destinationLandmark], routePreferences,
30 (err, routes) {
31 // If the route calculation is finished, we don't have a progress listener anymore.
32 _routingHandler = null;
33 ScaffoldMessenger.of(context).clearSnackBars();
34
35 // If there aren't any errors, we display the routes.
36 if (err == GemError.success) {
37 // Get the routes collection from map preferences.
38 final routesMap = _mapController.preferences.routes;
39
40 // Display the routes on map.
41 for (final route in routes!) {
42 routesMap.add(route, route == routes.first,
43 label: route.getMapLabel());
44 }
45
46 // Center the camera on routes.
47 _mapController.centerOnRoutes(routes: routes);
48 setState(() {
49 _routes = routes;
50 });
51 }
52 });
53
54 setState(() {});
55}
56
57void _onClearRoutesButtonPressed() {
58 // Remove the routes from map.
59 _mapController.preferences.routes.clear();
60
61 setState(() {
62 _routes = null;
63 });
64}
65
66void _onCancelRouteButtonPressed() {
67 // If we have a progress listener we cancel the route calculation.
68 if (_routingHandler != null) {
69 RoutingService.cancelRoute(_routingHandler!);
70
71 setState(() {
72 _routingHandler = null;
73 });
74 }
75}
This code handles the calculation of routes between two landmarks, displays the routes on the map, and provides options to cancel or clear the routes. The map is centered on the calculated routes, and a label showing the distance and duration is displayed.
Route Selection¶
1// In order to be able to select an alternative route, we have to register the route tap gesture callback.
2void _registerRouteTapCallback() {
3 // Register the generic map touch gesture.
4 _mapController.registerTouchCallback((pos) async {
5 // Select the map objects at given position.
6 _mapController.setCursorScreenPosition(pos);
7
8 // Get the selected routes.
9 final routes = _mapController.cursorSelectionRoutes();
10
11 // If there is a route at position, we select it as the main one on the map.
12 if (routes.isNotEmpty) {
13 _mapController.preferences.routes.mainRoute = routes[0];
14 }
15 });
16}
This code enables the user to select a specific route on the map by tapping on it. The selected route becomes the main route displayed.
Displaying Route Information¶
1// Define an extension for route for calculating the route label which will be displayed on map.
2extension RouteExtension on Route {
3 String getMapLabel() {
4 final totalDistance = getTimeDistance().unrestrictedDistanceM +
5 getTimeDistance().restrictedDistanceM;
6 final totalDuration =
7 getTimeDistance().unrestrictedTimeS + getTimeDistance().restrictedTimeS;
8
9 return '${_convertDistance(totalDistance)} \n${_convertDuration(totalDuration)}';
10 }
11
12 // Utility function to convert the meters distance into a suitable format.
13 String _convertDistance(int meters) {
14 if (meters >= 1000) {
15 double kilometers = meters / 1000;
16 return '${kilometers.toStringAsFixed(1)} km';
17 } else {
18 return '${meters.toString()} m';
19 }
20 }
21
22 // Utility function to convert the seconds duration into a suitable format.
23 String _convertDuration(int seconds) {
24 int hours = seconds ~/ 3600; // Number of whole hours
25 int minutes = (seconds % 3600) ~/ 60; // Number of whole minutes
26
27 String hoursText = (hours > 0) ? '$hours h ' : ''; // Hours text
28
29
30 String minutesText = '$minutes min'; // Minutes text
31
32 return hoursText + minutesText;
33 }
34}
This code defines an extension on the Route class that calculates and formats the distance and duration of the route for display on the map.