Skip to content

Finger Route

This example demonstrates how to create a Flutter app that allows users to draw a route on a map using their finger, calculates the route based on the drawn waypoints, and displays it using GemKit.

finger_route - example flutter screenshot

Setup

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

Prerequisites

Make sure you completed the Environment Setup - Flutter Examples guide before starting this guide.

Build and Run

Navigate to the finger_route 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:

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:

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
or
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
or
flutter run --release

How It Works

finger_route - example flutter screenshot

The example app demonstrates the following features:

  • Allow users to draw a route on the map with their finger.

  • Calculate a route based on the drawn waypoints.

  • Display the route on a map and provide options to cancel or clear the routes.

 1import 'package:gem_kit/core.dart';
 2import 'package:gem_kit/map.dart';
 3import 'package:gem_kit/routing.dart';
 4import 'package:flutter/cupertino.dart' hide Route;
 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: 'Finger 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  bool _areRoutesBuilt = false;
26  bool _isInDrawingMode = false;
27
28  @override
29  void dispose() {
30    GemKit.release();
31    super.dispose();
32  }
33
34  @override
35  Widget build(BuildContext context) {
36    return Scaffold(
37      appBar: AppBar(
38        backgroundColor: Colors.deepPurple[900],
39        title: const Text('Finger Route', style: TextStyle(color: Colors.white)),
40        actions: [
41          // Enable drawing mode.
42          if (_routingHandler == null && !_areRoutesBuilt && !_isInDrawingMode)
43            IconButton(
44              onPressed: () => _onDrawPressed(),
45              icon: const Icon(CupertinoIcons.hand_draw, color: Colors.white),
46            ),
47          // Build route from drawn waypoints.
48          if (_routingHandler == null && !_areRoutesBuilt && _isInDrawingMode)
49            IconButton(
50              onPressed: () => _onBuildRouteButtonPressed(context),
51              icon: const Icon(Icons.done, color: Colors.white),
52            ),
53          // Cancel route calculation.
54          if (_routingHandler != null)
55            IconButton(
56              onPressed: () => _onCancelRouteButtonPressed(),
57              icon: const Icon(Icons.stop, color: Colors.white),
58            ),
59          // Clear the drawn routes.
60          if (_areRoutesBuilt)
61            IconButton(
62              onPressed: () => _onClearRoutesButtonPressed(),
63              icon: const Icon(Icons.clear, color: Colors.white),
64            ),
65        ],
66      ),
67      body: GemMap(
68        onMapCreated: _onMapCreated,
69      ),
70    );
71  }

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 drawing, building, canceling, and clearing routes.

Drawing and Route Calculation

finger_route - example flutter screenshot

 1// The callback for when the map is ready to use.
 2void _onMapCreated(GemMapController controller) {
 3  // Save controller for further usage.
 4  _mapController = controller;
 5}
 6
 7void _onDrawPressed() {
 8  _mapController.enableDrawMarkersMode();
 9  setState(() {
10    _isInDrawingMode = true;
11  });
12}
13
14void _onBuildRouteButtonPressed(BuildContext context) {
15  final waypoints = _mapController.disableDrawMarkersMode();
16
17  // Define the route preferences.
18  final routePreferences = RoutePreferences(
19      accurateTrackMatch: false, ignoreRestrictionsOverTrack: true);
20
21  _showSnackBar(context, message: "The route is being calculated.");
22
23  _routingHandler = RoutingService.calculateRoute(waypoints, routePreferences,
24      (err, routes) {
25    setState(() {
26      _routingHandler = null;
27      _isInDrawingMode = false;
28    });
29
30    ScaffoldMessenger.of(context).clearSnackBars();
31
32    if (err == GemError.success) {
33      final routesMap = _mapController.preferences.routes;
34
35      for (final route in routes!) {
36        routesMap.add(route, route == routes.first,
37            label: route.getMapLabel());
38      }
39
40      _mapController.centerOnRoutes(routes: routes);
41      setState(() {
42        _areRoutesBuilt = true;
43      });
44    }
45  });
46
47  setState(() {});
48}
49
50void _onClearRoutesButtonPressed() {
51  // Remove the routes from map.
52  _mapController.preferences.routes.clear();
53
54  setState(() {
55    _areRoutesBuilt = false;
56  });
57}
58
59void _onCancelRouteButtonPressed() {
60  // If we have a progress listener, cancel the route calculation.
61  if (_routingHandler != null) {
62    RoutingService.cancelRoute(_routingHandler!);
63
64    setState(() {
65      _routingHandler = null;
66    });
67  }
68}

This code handles drawing waypoints on the map, calculating the route based on those waypoints, 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.

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    String minutesText = '$minutes min'; // Minutes text
29
30    return hoursText + minutesText;
31  }
32}

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.

Flutter Examples

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