Skip to content

Calculate route

In this guide you will learn how to calculate a preset route and center the interactive map on the search result.

calculate_route - example flutter screenshot

Setup

First, get an API key token, see the Getting Started guide.

Prerequisites

It is required that you complete the Environment Setup - Flutter Examples guide before starting this guide.

Build and run

Start a terminal/command prompt and go to the calculate_route directory, within the flutter examples directory - that is the name of this example project.

calculate_route - example flutter screenshot

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:

example flutter upgrade screenshot

flutter upgrade

example flutter clean screenshot

run the following terminal commands in the project directory, where the pubspec.yaml file is located:

flutter clean

example flutter pub get screenshot

flutter pub get

Run the example:

flutter run

select chrome - example flutter screenshot

If such a question appears, select the chrome browser; in the above example, press 2.

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            // TODO: Add your own signing config for the release build.
12            // Signing with the debug keys for now, so `flutter run --release` works.
13            minifyEnabled false
14            shrinkResources false
15            signingConfig signingConfigs.debug
16        }
17    }
18}

Then build the apk:

flutter build apk --debug
or
flutter build apk --release
the apk file is located in the build/app/outputs/apk/debug or build/app/outputs/apk/release subdirectory, for debug or release build respectively, within the current project directory, such as center_coordinates
The apk file name is app-release.apk or app-debug.apk
You can copy the apk to an android device using adb, for example:
adb push app-release.apk sdcard

And then click on the apk in the file browser on the device to install and run it.

In the ios/Podfile configuration text file, at the top, set the minimum ios platform to 13 like this:

platform :ios, '13.0'

Run pod install in the [ios folder] ./ios/
Then go back to the repository root folder and type flutter build ios to build a Runner.app.
Type flutter run to build and run on an attached device.
You can open the <path/to>/ios/Runner.xcworkspace project in Xcode and execute and debug from there.

How it works

calculate_route - example flutter screenshot

In the example project directory, such as center_coordinates, there is a text file named pubspec.yaml which contains project configuration and dependencies. The most important lines from this file are shown here:

 1name: center_coordinates
 2description: A Flutter example using Maps SDK for Flutter.
 3
 4version: 1.0.0+1
 5
 6environment:
 7  sdk: '>=3.0.5 <4.0.0'
 8
 9dependencies:
10  flutter:
11    sdk: flutter
12  gem_kit:
13    path: plugins/gem_kit
14
15  cupertino_icons: ^1.0.2
16
17  dev_dependencies:
18    flutter_test:
19      sdk: flutter
20
21    flutter_lints: ^3.0.2
22
23# The following section is specific to Flutter packages.
24flutter:
25  uses-material-design: true

The project must have a name and version. The dependencies list the Flutter SDK, and the gem_kit, Maps for Flutter SDK.

The source code is in example_pathname/lib/main.dart Replace example_pathname with the actual example path name, such as center_coordinates

 1import 'package:gem_kit/core.dart';
 2import 'package:gem_kit/map.dart';
 3import 'package:gem_kit/routing.dart';
 4import 'package:flutter/material.dart' hide Route;
 5
 6Future<void> main() async {
 7  const String projectApiToken = "YOUR_API_KEY_TOKEN";
 8  await GemKit.initialize(appAuthorization: projectApiToken);
 9  runApp(const MyApp());
10}
11class MyApp extends StatelessWidget {
12  const MyApp({super.key});
13  @override
14  Widget build(BuildContext context) {
15    return const MaterialApp(
16      debugShowCheckedModeBanner: false,
17      title: 'Calculate Route',
18      home: MyHomePage(),
19    );
20  }
21}

The dart material package is imported, as well as the required gem_kit packages. The map is in a widget which is the root of the application.

calculate_route - example flutter screenshot

 1void _onBuildRouteButtonPressed(BuildContext context) {
 2   // Define the departure.
 3   final departureLandmark = Landmark.withLatLng(latitude: 48.85682, longitude: 2.34375);
 4
 5   // Define the destination.
 6   final destinationLandmark = Landmark.withLatLng(latitude: 50.84644, longitude: 4.34587);
 7
 8   // Define the route preferences.
 9   final routePreferences = RoutePreferences();
10
11   _showSnackBar(context, message: "The route is being calculated.");
12
13   // Calling the calculateRoute SDK method.
14   // (err, results) - is a callback function that gets called when the route computing is finished.
15   // err is an error enum, results is a list of routes.
16
17   _routingHandler =
18     RoutingService.calculateRoute([departureLandmark, destinationLandmark], routePreferences, (err, routes) {
19     // If the route calculation is finished, we don't have a progress listener anymore.
20     _routingHandler = null;
21     ScaffoldMessenger.of(context).clearSnackBars();
22
23     // If there aren't any errors, we display the routes.
24     if (err == GemError.success) {
25         // Get the routes collection from map preferences.
26         final routesMap = _mapController.preferences.routes;
27
28         // Display the routes on map.
29         for (final route in routes!) {
30           routesMap.add(route, route == routes.first, label: route.getMapLabel());
31         }
32         // Center the camera on routes.
33         _mapController.centerOnRoutes(routes);
34         setState(() {
35           _routes = routes;
36         });
37     }
38   });
39   setState(() {});
40}

calculate_route - example flutter screenshot

To compute a route, at least two waypoints (landmarks) are required, one for the departure position, and the other for the destination position. Optionally, zero or more intermediate waypoints can be added. In this example, there are two landmarks.
Each landmark specifies its longitude, latitude coordinate pair, one for the departure position, the other for the destination position.
Also, a RoutePreferences object is instantiated, but not configured, so the default settings are used. RoutingService.calculateRoute() calculates the route, passing in the list of landmarks, in order, from departure to destination, and a route preferences instance.
If there is no error, (err == GemError.success), the routes are added to the map, routesMap.add() to be displayed.
The map is centered on the group of resulting routes, such that they fit in the viewport.
_mapController.centerOnRoutes(routes);

calculate_route - example flutter screenshot

Flutter Examples

Maps SDK for Flutter Examples can be downloaded or cloned with Git