Skip to content

Human Voices

In this guide you will learn how to add voice guidance to a simulated navigation on an interactive map.

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.

Run the example

Start a terminal/command prompt and go to the human_voices directory, within the flutter examples directory

Build and run the example:

Build and run

human_voices - 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. human_voices/plugins/gem_kit - see the environment setup guide above.

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

human_voices - 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}

Voice guidance requires that 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:

 1android {
 2    defaultConfig {
 3        applicationId "com.magiclane.gem_kit.examples.human_voices"
 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, which is human_voices in this case.
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

In the human_voices project directory, 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: human_voices
 2version: 1.0.0+1
 3
 4environment:
 5  sdk: '>=3.0.5 <4.0.0'
 6
 7dependencies:
 8  flutter:
 9    sdk: flutter
10  gem_kit:
11    path: plugins/gem_kit
12
13  cupertino_icons: ^1.0.2
14  intl: ^0.18.1
15  flutter_tts: ^3.7.0
16
17# The following section is specific to Flutter packages.
18flutter:
19  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 tts (text to speech) source code is in human_voices/lib/tts_engine.dart In this basic example, only the volume, pitch and rate can be adjusted, not the language or speaker.

The app source code is in human_voices/lib/main.dart

 1import 'package:flutter/cupertino.dart';
 2import 'package:human_voices/bottom_navigation_panel.dart';
 3import 'package:human_voices/instruction_model.dart';
 4import 'package:human_voices/top_navigation_panel.dart';
 5import 'package:human_voices/tts_engine.dart';
 6import 'package:human_voices/utility.dart';
 7
 8import 'package:gem_kit/gem_kit_basic.dart';
 9import 'package:gem_kit/gem_kit_map_controller.dart';
10import 'package:gem_kit/api/gem_mapviewpreferences.dart' as gem;
11import 'package:gem_kit/api/gem_navigationservice.dart';
12import 'package:gem_kit/api/gem_coordinates.dart';
13import 'package:gem_kit/api/gem_landmark.dart';
14import 'package:gem_kit/api/gem_routingpreferences.dart';
15import 'package:gem_kit/api/gem_sdksettings.dart';
16import 'package:gem_kit/api/gem_routingservice.dart' as gem;
17import 'package:gem_kit/widget/gem_kit_map.dart';
18import 'package:flutter/material.dart';
19
20void main() {
21  runApp(const MyApp());
22}
23
24class MyApp extends StatelessWidget {
25  const MyApp({super.key});
26
27  @override
28  Widget build(BuildContext context) {
29    return const MaterialApp(
30      debugShowCheckedModeBanner: false,
31      title: 'Build route example',
32      home: MyHomePage(),
33    );
34  }
35}
36
37class MyHomePage extends StatefulWidget {
38  const MyHomePage({super.key});
39
40  @override
41  State<MyHomePage> createState() => _MyHomePageState();
42}

First, the dart material and cupertino packages are imported, followed by the gem_kit packages for the map controller, which enables user input such as pan and zoom, the map package which draws the map, the settings and preferences packages, the coordinates, landmark, routing and navigation packages, as well as the panels of this example, used to display text, picture(icon) as well as play the voice instructions..

The map is in a widget which is the root of the application.

 1class _MyHomePageState extends State<MyHomePage> {
 2  late GemMapController _mapController;
 3  late SdkSettings _sdkSettings;
 4  late gem.RoutingService _routingService;
 5  late NavigationService _navigationService;
 6  late InstructionModel currentInstruction;
 7  late TTSEngine _ttsEngine;
 8
 9  List<Coordinates> waypoints = [];
10  List<gem.Route> shownRoutes = [];
11
12  bool haveRoutes = false;
13  bool isNavigating = false;
14  bool hasVolume = true;
15
16  @override
17  void initState() {
18    super.initState();
19    waypoints.add(Coordinates(
20        latitude: 48.87586140402999, longitude: 2.3031139990581493));
21    waypoints.add(Coordinates(
22        latitude: 48.87422484785287, longitude: 2.2995244508179242));
23    waypoints.add(Coordinates(
24        latitude: 48.873618858675435, longitude: 2.2951312439853533));
25  }
26
27  Future<void> onMapCreated(GemMapController controller) async {
28    _mapController = controller;
29    SdkSettings.create(_mapController.mapId).then((value) {
30      _sdkSettings = value;
31      _sdkSettings.setAppAuthorization('YOUR_API_KEY_TOKEN');
32    });
33
34    _routingService = await gem.RoutingService.create(_mapController.mapId);
35    _navigationService = await NavigationService.create(controller.mapId);
36    _ttsEngine = TTSEngine();
37    _ttsEngine.initTts();
38  }

The map is initialized with the map controller and the settings.

The waypoints for the departure and destination positions are hardcoded in the void initState() function shown above. At least 2 waypoints are required to compute a route. The first waypoint in the list is the departure position, and the last one is the destination.

If there are more waypoints, the intermediate ones are waypoints through which the route should pass, in the order in which they are added to the list. In the above case, there is a single additional waypoint between the departure and the destination positions.

Setting the API key

The string "YOUR_API_KEY_TOKEN" should be replaced with your actual API key token string.

human_voices - example flutter screenshot

 1_onPressed(List<Coordinates> waypoints, BuildContext context) async {
 2 // Create a landmark list
 3 final landmarkWaypoints =
 4     await gem.LandmarkList.create(_mapController.mapId);
 5
 6 // Create landmarks from coordinates and add them to the list
 7 for (final wp in waypoints) {
 8   var landmark = await Landmark.create(_mapController.mapId);
 9   await landmark.setCoordinates(
10       Coordinates(latitude: wp.latitude, longitude: wp.longitude));
11   landmarkWaypoints.push_back(landmark);
12 }
13
14 final routePreferences = RoutePreferences();
15
16 var result = await _routingService.calculateRoute(
17     landmarkWaypoints, routePreferences, (err, routes) async {
18   if (err != GemError.success || routes == null) {
19     return;
20   } else {
21     // Get the controller's preferences
22     final mapViewPreferences = await _mapController.preferences();
23     // Get the routes from the preferences
24     final routesMap = await mapViewPreferences.routes();
25     //Get the number of routes
26     final routesSize = await routes.size();
27
28     for (int i = 0; i < routesSize; i++) {
29       final route = await routes.at(i);
30       shownRoutes.add(route);
31
32       final timeDistance = await route.getTimeDistance();
33
34       final totalDistance = convertDistance(
35           timeDistance.unrestrictedDistanceM +
36               timeDistance.restrictedDistanceM);
37
38       final totalTime = convertDuration(
39           timeDistance.unrestrictedTimeS + timeDistance.restrictedTimeS);
40       // Add labels to the routes
41       await routesMap.add(route, i == 0,
42           label: '$totalDistance \n $totalTime');
43     }
44     // Select the first route as the main one
45     final mainRoute = await routes.at(0);
46
47     await _mapController.centerOnRoute(mainRoute);
48   }
49 });
50
51 setState(() {
52   haveRoutes = true;
53 });
54 return result;
55}

This is the custom method for calling calculateRoute, selecting the first route (at index 0) from the resulting list of routes and set it as the mainRoute, then center the map on this route using centerOnRoute(mainRoute) so it fits in the viewport.

 1_navigateOnRoute(
 2   {required gem.Route route,
 3   required Function(InstructionModel) onInstructionUpdated}) async {
 4 await _navigationService.startSimulation(route, (type, instruction) async {
 5   if (type != NavigationEventType.navigationInstructionUpdate ||
 6       instruction == null) {
 7     setState(() {
 8       isNavigating = false;
 9       _removeRoutes(shownRoutes);
10     });
11     return;
12   }
13   isNavigating = true;
14
15   final ins = await InstructionModel.fromGemInstruction(instruction);
16   onInstructionUpdated(ins);
17
18   instruction.dispose();
19 }, onTextToSpeechInstruction: (textToSpeech) {
20   _ttsEngine.speakText(textToSpeech);
21 });
22}

This method creates the simulation.

human_voices - example flutter screenshot

Note that the volume icon on the right indicates that voice instructions are not muted.

 1_startSimulation(gem.Route route) async {
 2 await _navigateOnRoute(
 3     route: route,
 4     onInstructionUpdated: (instruction) {
 5       currentInstruction = instruction;
 6       setState(() {});
 7     });
 8
 9 _mapController.startFollowingPosition(
10     animation: gem.GemAnimation(
11         duration: 200, type: gem.EAnimation.AnimationLinear));
12}

This method starts the simulated navigation and starts following the moving position tracker.

 1_removeRoutes(List<gem.Route> routes) async {
 2 final prefs = await _mapController.preferences();
 3 final routesMap = await prefs.routes();
 4
 5 for (final route in routes) {
 6   routesMap.remove(route);
 7 }
 8
 9 shownRoutes.clear();
10 setState(() {
11   haveRoutes = false;
12   isNavigating = false;
13 });
14}

This method removes the rendered routes from the map.

1_stopSimulation(List<gem.Route> routes) async {
2 await _navigationService.cancelNavigation();
3 _removeRoutes(routes);
4 hasVolume = true;
5}

This method stops the simulated navigation and removes the rendered routes from the map.

human_voices - example flutter screenshot

Note that the volume icon on the right indicates that voice instructions are muted.

1_setVolume() {
2 double volume = hasVolume ? 0.0 : 1.0;
3 _ttsEngine.setVolume(volume);
4 hasVolume = !hasVolume;
5}

This method mutes / unmutes the voice instructions.