GPX Route Example¶
Setup¶
Prerequisites¶
Build and Run¶
Go to the gpx_route
directory within the Flutter examples directory. This is the name of this example project.
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 following code demonstrates the main components of the GPX route example:
1import 'package:gem_kit/core.dart';
2import 'package:gem_kit/map.dart';
3import 'package:gem_kit/navigation.dart';
4import 'package:gem_kit/routing.dart';
5import 'package:path_provider/path_provider.dart';
6import 'package:flutter/material.dart' hide Route;
7import 'package:flutter/services.dart';
8import 'dart:async';
9import 'dart:io';
10
11Future<void> main() async {
12 const projectApiToken = String.fromEnvironment('GEM_TOKEN');
13 await GemKit.initialize(appAuthorization: projectApiToken);
14 runApp(const MyApp());
15}
16
17class MyApp extends StatelessWidget {
18 const MyApp({super.key});
19
20 @override
21 Widget build(BuildContext context) {
22 return const MaterialApp(
23 debugShowCheckedModeBanner: false,
24 title: 'GPX Route',
25 home: MyHomePage(),
26 );
27 }
28}
The above code imports the necessary Dart and GemKit packages and initializes the app with the projectApiToken. The main widget MyApp serves as the root of the application, displaying the GPX route on a map.
Map Initialization¶
The following code initializes the map when it is ready to be used:
1void _onMapCreated(GemMapController controller) {
2 // Save controller for further usage.
3 _mapController = controller;
4}
This callback function is called when the interactive map is initialized and ready to use. The map controller is stored for later use.
Copying the GPX File¶
This function copies the recorded_route.gpx file from the assets directory to the app’s documents directory:
1Future<void> _copyGpxToAppDocsDir() async {
2 final docDirectory = await getApplicationDocumentsDirectory();
3 final gpxFile = File('${docDirectory.path}/recorded_route.gpx');
4 final imageBytes = await rootBundle.load('assets/recorded_route.gpx');
5 final buffer = imageBytes.buffer;
6 await gpxFile.writeAsBytes(
7 buffer.asUint8List(imageBytes.offsetInBytes, imageBytes.lengthInBytes),
8 );
9}
The function ensures that the GPX file is available in the app’s documents directory, ready for use during runtime.
Importing GPX Data and Calculating Routes¶
This function reads GPX data from the file, calculates the routes, and displays them on the map:
1Future<void> _importGPX() async {
2 _showSnackBar(context, message: 'The route is calculating.');
3
4 final docDirectory = await getApplicationDocumentsDirectory();
5 final gpxFile = File('${docDirectory.path}/recorded_route.gpx');
6
7 if (!await gpxFile.exists()) {
8 print('GPX file does not exist (${gpxFile.path})');
9 return;
10 }
11
12 final bytes = await gpxFile.readAsBytes();
13 final pathData = Uint8List.fromList(bytes);
14 final gemPath = Path.create(data: pathData, format: 0);
15 final landmarkList = gemPath.toLandmarkList();
16
17 print("GPX Landmarklist size: ${landmarkList.length}");
18
19 final routePreferences =
20 RoutePreferences(transportMode: RouteTransportMode.bicycle);
21
22 RoutingService.calculateRoute(
23 landmarkList,
24 routePreferences,
25 (err, routes) {
26 ScaffoldMessenger.of(context).clearSnackBars();
27
28 if (err == GemError.success) {
29 final routesMap = _mapController.preferences.routes;
30
31 for (final route in routes!) {
32 routesMap.add(route, route == routes.first, label: route.getMapLabel());
33 }
34
35 _mapController.centerOnRoutes(routes: routes);
36
37 setState(() {
38 _areRoutesBuilt = true;
39 });
40 }
41 },
42 );
43 _isGpxDataLoaded = true;
44}
Starting and Stopping the Simulation¶
The simulation can be started or stopped using the following functions:
1void _startSimulation() {
2 if (_isSimulationActive) return;
3 if (!_isGpxDataLoaded) return;
4
5 final routes = _mapController.preferences.routes;
6
7 _navigationHandler = NavigationService.startSimulation(
8 routes.mainRoute,
9 (eventType, instruction) {
10 // Navigation instruction callback.
11 },
12 speedMultiplier: 2,
13 );
14
15 _mapController.startFollowingPosition();
16
17 setState(() => _isSimulationActive = true);
18}
19
20void _stopSimulation() {
21 _mapController.preferences.routes.clear();
22
23 setState(() => _areRoutesBuilt = false);
24
25 if (_isSimulationActive) {
26 NavigationService.cancelNavigation(_navigationHandler!);
27 _navigationHandler = null;
28
29 setState(() => _isSimulationActive = false);
30 }
31}
Utility Functions¶
Utility functions are also included to display messages and format route labels:
1void _showSnackBar(BuildContext context,
2 {required String message, Duration duration = const Duration(hours: 1)}) {
3 final snackBar = SnackBar(
4 content: Text(message),
5 duration: duration,
6 );
7
8 ScaffoldMessenger.of(context).showSnackBar(snackBar);
9}
1extension RouteExtension on Route {
2 String getMapLabel() {
3 final totalDistance = getTimeDistance().unrestrictedDistanceM +
4 getTimeDistance().restrictedDistanceM;
5 final totalDuration =
6 getTimeDistance().unrestrictedTimeS + getTimeDistance().restrictedTimeS;
7
8 return '${_convertDistance(totalDistance)} \n${_convertDuration(totalDuration)}';
9 }
10
11 String _convertDistance(int meters) {
12 if (meters >= 1000) {
13 double kilometers = meters / 1000;
14 return '${kilometers.toStringAsFixed(1)} km';
15 } else {
16 return '${meters.toString()} m';
17 }
18 }
19
20 String _convertDuration(int seconds) {
21 int hours = seconds ~/ 3600;
22 int minutes = (seconds % 3600) ~/ 60;
23
24 String hoursText = (hours > 0) ? '$hours h ' : '';
25 String minutesText = '$minutes min';
26
27 return hoursText + minutesText;
28 }
29}
The _showSnackBar method displays messages during route calculation. The RouteExtension is an extension that formats route labels to display the total distance and duration.