Navigate Route¶
Setup¶
Prerequisites¶
Run the example¶
Start a terminal/command prompt and go to the navigate_route
directory,
within the flutter examples directory
Build and run the example:
Build and run¶
Note - the gem_kit
directory containing the Maps SDK for Flutter
should be in the plugins
directory of the example, e.g.
navigate_route/plugins/gem_kit
- see the environment setup guide above.
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:
flutter run
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/app/src/main/AndroidManifest.xml
add the location permissions
required for actual navigation, below the top <manifest xmlns:android
line,
as shown:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
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 minSdkVersion
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.navigate_route"
4 minSdkVersion 21
5 targetSdkVersion flutter.targetSdkVersion
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
flutter build apk --release
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 navigate_route
in this case.app-release.apk
or app-debug.apk
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'
Also in the ios/Podfile
configuration text file, add the location permissions
required for actual navigation, at the end of the file, as shown:
1post_install do |installer|
2 installer.pods_project.targets.each do |target|
3 flutter_additional_ios_build_settings(target)
4
5 target.build_configurations.each do |config|
6 config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [
7 '$(inherited)',
8 ## dart: [PermissionGroup.location, PermissionGroup.locationAlways, PermissionGroup.locationWhenInUse]
9 'PERMISSION_LOCATION=1',
10 ]
11 end
12 end
13end
In the ios/Runner/Info.plist
configuration text file, add the following
lines inside the <dict> </dict>
block:
<key>NSLocationWhenInUseUsageDescription</key>
<string>Location is needed for map localization and navigation</string>
pod install
in the [ios folder] ./ios/
flutter build ios
to build a Runner.app.flutter run
to build and run on an attached device.<path/to>/ios/Runner.xcworkspace
project in Xcode
and execute and debug from there.How it works¶
In the navigate_route
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: navigate_route
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 permission_handler: ^10.4.2
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 source code is in navigate_route/lib/main.dart
1import 'package:navigate_route/bottom_navigation_panel.dart';
2import 'package:navigate_route/instruction_model.dart';
3import 'package:navigate_route/position_model.dart';
4import 'package:navigate_route/top_navigation_panel.dart';
5import 'package:navigate_route/utility.dart';
6
7import 'package:gem_kit/gem_kit_basic.dart';
8import 'package:gem_kit/gem_kit_map_controller.dart';
9import 'package:gem_kit/gem_kit_position.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';
18
19import 'dart:async';
20import 'package:flutter/material.dart';
21import 'package:flutter/foundation.dart';
22import 'package:permission_handler/permission_handler.dart';
23
24void main() {
25 runApp(const MyApp());
26}
27
28class MyApp extends StatelessWidget {
29 const MyApp({super.key});
30
31 // This widget is the root of your application.
32 @override
33 Widget build(BuildContext context) {
34 return const MaterialApp(
35 debugShowCheckedModeBanner: false,
36 title: 'Navigate route',
37 home: MyHomePage(),
38 );
39 }
40}
41
42class MyHomePage extends StatefulWidget {
43 const MyHomePage({super.key});
44
45 @override
46 State<MyHomePage> createState() => _MyHomePageState();
47}
The dart
material package is imported, as well as 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 routingservice which computes
a route, the landmark and coordinates packages for geolocation,
the navigationservice package which carries out both simulated and actual
navigation, and the settings and map preferences packages.
Note that, in addition to the gem_kit packages imported for simulation, navigation also requires the position package.
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 PositionService _positionService;
7 late InstructionModel currentInstruction;
8 PermissionStatus locationPermissionStatus = PermissionStatus.denied;
9
10 List<Coordinates> mywaypoints = [];
11 List<gem.Route> shownRoutes = [];
12
13 bool haveRoutes = false;
14 bool isNavigating = false;
15 PositionModel currentPosition = PositionModel(
16 latitude: 48.859935072481264,
17 longitude: 2.294484386370221,
18 altitude: 0,
19 speed: 0);
20
21 @override
22 void initState() {
23 super.initState();
24 }
25
26 Future<void> onMapCreated(GemMapController controller) async {
27 _mapController = controller;
28 SdkSettings.create(_mapController.mapId).then((value) {
29 _sdkSettings = value;
30 _sdkSettings.setAppAuthorization("YOUR_API_KEY_TOKEN");
31 });
32
33 _routingService = await gem.RoutingService.create(_mapController.mapId);
34 _navigationService = await NavigationService.create(controller.mapId);
35 _positionService = await PositionService.create(_mapController.mapId);
36 }
The map is initialized with the map controller and the settings.
In addition to the RoutingService
and NavigationService
, also required
for simulation, actual navigation also requires a PositionService
to be
instantiated. The current position is initialized in Paris until a GPS
position is obtained from the device, which requires user permission first.
Setting the API key¶
The string |
A tap on the arrow button at the top right causes a set of routes to be computed and rendered on the map.
1// Method for asking for location permission
2_askForLocation() async {
3 if (kIsWeb) {
4 await _positionService.setLiveDataSource();
5 await _positionService.addPositionListener((pos) {
6 currentPosition = PositionModel(
7 latitude: pos.coordinates.latitude,
8 longitude: pos.coordinates.longitude,
9 altitude: pos.coordinates.altitude,
10 speed: pos.speed);
11 });
12 setState(() {
13 locationPermissionStatus = PermissionStatus.granted;
14 });
15 } else {
16 if (locationPermissionStatus == PermissionStatus.granted) {
17 return;
18 }
19 locationPermissionStatus = await Permission.locationWhenInUse.request();
20
21 if (locationPermissionStatus == PermissionStatus.granted) {
22 await _mapController.startFollowingPosition();
23 await _positionService.addPositionListener((pos) {
24 currentPosition = PositionModel(
25 latitude: pos.coordinates.latitude,
26 longitude: pos.coordinates.longitude,
27 altitude: pos.coordinates.altitude,
28 speed: pos.speed);
29 });
30 setState(() {});
31 }
32 }
33}
This is the method to ask location permission from the user, as actual navigation requires a live GPS position from the device GPS sensor.
1// Method for calling calculate route and displaying the results
2_onPressed(BuildContext context) async {
3 mywaypoints.add(Coordinates(
4 latitude: currentPosition.latitude,
5 longitude: currentPosition.longitude));
6 mywaypoints.add(Coordinates(
7 latitude: 44.42453081911026, longitude: 26.101618214626367));
8
9 // Create a landmark list
10 final landmarkWaypoints =
11 await gem.LandmarkList.create(_mapController.mapId);
12
13 // Create landmarks from coordinates and add them to the list
14 for (final wp in mywaypoints) {
15 var landmark = await Landmark.create(_mapController.mapId);
16 await landmark.setCoordinates(
17 Coordinates(latitude: wp.latitude, longitude: wp.longitude));
18 landmarkWaypoints.push_back(landmark);
19 }
20 final routePreferences = RoutePreferences();
21
22 var result = await _routingService.calculateRoute(
23 landmarkWaypoints, routePreferences, (err, routes) async {
24 if (err != GemError.success || routes == null) {
25 return;
26 } else {
27 // Get the controller's preferences
28 final mapViewPreferences = await _mapController.preferences();
29 // Get the routes from the preferences
30 final routesMap = await mapViewPreferences.routes();
31 //Get the number of routes
32 final routesSize = await routes.size();
33
34 for (int i = 0; i < routesSize; i++) {
35 final route = await routes.at(i);
36 shownRoutes.add(route);
37 final timeDistance = await route.getTimeDistance();
38
39 final totalDistance = convertDistance(
40 timeDistance.unrestrictedDistanceM +
41 timeDistance.restrictedDistanceM);
42
43 final totalTime = convertDuration(
44 timeDistance.unrestrictedTimeS + timeDistance.restrictedTimeS);
45 // Add labels to the routes
46 await routesMap.add(route, i == 0,
47 label: '$totalDistance \n $totalTime');
48 }
49 // Select the first route as the main one
50 final mainRoute = await routes.at(0);
51 await _mapController.centerOnRoute(mainRoute);
52 }
53 });
54 setState(() {
55 haveRoutes = true;
56 });
57 return result;
58}
This is the custom method to compute a route by calling:
_routingService.calculateRoute()
,
rendering the resulting set of routes on the map,
then choosing the route at index 0 (the first one),
setting it as the mainRoute
and then
centering the main route so it fits in the viewport:
_mapController.centerOnRoute()
1// Method for creating the simulation
2_navigateOnRoute(
3 {required gem.Route route,
4 required Function(InstructionModel) onInstructionUpdated}) async {
5 await _navigationService.startNavigation(route, (type, instruction) async {
6 if (type != NavigationEventType.navigationInstructionUpdate ||
7 instruction == null) {
8 setState(() {
9 isNavigating = false;
10 _removeRoutes(shownRoutes);
11 });
12 return;
13 }
14 isNavigating = true;
15 final ins = await InstructionModel.fromGemInstruction(instruction);
16 onInstructionUpdated(ins);
17 instruction.dispose();
18 });
19}
20
21// Method for starting the simulation and following the position
22_startNavigation(gem.Route route) async {
23 await _navigateOnRoute(
24 route: route,
25 onInstructionUpdated: (instruction) {
26 currentInstruction = instruction;
27 setState(() {});
28 });
29 _mapController.startFollowingPosition(
30 animation:
31 gem.GemAnimation(duration: 200, type: gem.EAnimation.AnimationLinear));
32}
Actual navigation along the route is started by
await _navigationService.startNavigation()
as compared to navigation simulation along the route, which
would have been started by
await _navigationService.startSimulation()
and the camera is set to follow the current position indicator arrow using
_mapController.startFollowingPosition()
A tap on the green arrow button at the top causes the navigation to start, and the camera to follow the position indicator.
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 shownRoutes.clear();
9 setState(() {
10 haveRoutes = false;
11 isNavigating = false;
12 });
13}
Function to remove the computed routes rendered on the map.
1// Method to stop the simulation and remove the displayed routes
2_stopNavigation(List<gem.Route> routes) async {
3 await _navigationService.cancelNavigation();
4 _removeRoutes(routes);
5}
Function implementing the red stop navigation button.
1@override
2Widget build(BuildContext context) {
3 return Scaffold(
4 appBar: AppBar(
5 title: const Text("Navigate route"),
6 backgroundColor: Colors.deepPurple[900],
7 actions: [
8 GestureDetector(
9 onTap: () => _startNavigation(shownRoutes[0]),
10 child: Icon(Icons.play_arrow,
11 size: 40,
12 color: haveRoutes
13 ? isNavigating
14 ? Colors.grey
15 : Colors.green
16 : Colors.grey),
17 ),
18 GestureDetector(
19 onTap: () => _stopNavigation(shownRoutes),
20 child: Icon(Icons.stop,
21 size: 40, color: haveRoutes ? Colors.red : Colors.grey),
22 ),
23 GestureDetector(
24 onTap: () => haveRoutes ? null : _onPressed(waypoints, context),
25 child: Icon(
26 Icons.directions,
27 size: 40,
28 color: haveRoutes ? Colors.grey : Colors.white,
29 ),
30 )
31 ],
32 ),
The green play button, the red stop button and the button to compute the routes.
1 body: Stack(children: [
2 GemMap(
3 onMapCreated: onMapCreated,
4 ),
5 if (isNavigating)
6 Positioned(
7 top: 40,
8 left: 10,
9 child: NavigationInstructionPanel(
10 instruction: currentInstruction,
11 ),
12 ),
13 if (isNavigating)
14 Positioned(
15 bottom: 30,
16 left: 0,
17 child: NavigationBottomPanel(
18 remainingDistance: currentInstruction.remainingDistance,
19 eta: currentInstruction.eta,
20 remainingDuration: currentInstruction.remainingDuration,
21 ),
22 ),
The top navigation panel, showing next turn icons and instructions, and the bottom navigation panel. These panels are shown when navigation, including simulated navigation, is active.
1 if (isNavigating)
2 Positioned(
3 top: MediaQuery.of(context).size.height * 0.26,
4 left: MediaQuery.of(context).size.width / 2 - 65,
5 child: GestureDetector(
6 onTap: () => _mapController.startFollowingPosition(),
7 child: InkWell(
8 child: Container(
9 height: 50,
10 padding: const EdgeInsets.symmetric(horizontal: 10),
11 decoration: BoxDecoration(
12 color: Colors.white,
13 borderRadius: const BorderRadius.all(Radius.circular(20)),
14 boxShadow: [
15 BoxShadow(
16 color: Colors.grey.withOpacity(0.5),
17 spreadRadius: 5,
18 blurRadius: 7,
19 offset: const Offset(0, 3),
20 ),
21 ],
22 ),
23 child: Row(
24 mainAxisAlignment: MainAxisAlignment.spaceBetween,
25 children: [
26 Icon(
27 Icons.navigation,
28 color: Theme.of(context).colorScheme.primary,
29 ),
30 const Text(
31 'Recenter',
32 style: TextStyle(
33 color: Colors.black,
34 fontSize: 16,
35 fontWeight: FontWeight.w600),
36 )
37 ],
38 ),
39 ),
40 ),
41 ),
42 ),
43 ]),
onTap: () => _mapController.startFollowingPosition()
1 resizeToAvoidBottomInset: false,
2 floatingActionButtonLocation:
3 isNavigating ? null : FloatingActionButtonLocation.endFloat,
4 floatingActionButton: isNavigating
5 ? null
6 : locationPermissionStatus != PermissionStatus.granted
7 ? FloatingActionButton(
8 backgroundColor: Colors.white,
9 onPressed: () => _askForLocation(),
10 child: const Icon(Icons.location_off, color: Colors.red),
11 )
12 : FloatingActionButton(
13 backgroundColor: Colors.white,
14 onPressed: () => _mapController.startFollowingPosition(),
15 child: const Icon(
16 Icons.location_on,
17 color: Colors.green,
18 ),
19 ),
20 );
21}
This is the floating position access permission request button in the lower right of the viewport. If location/position is not available because user permission has not yet been obtained, the button icon is red; otherwise it is green to indicate that position data from the device sensor is available.