Skip to content

GPX Route

This example demonstrates how to calculate a route based on GPX data, render and center the route on an interactive map, and navigate along the route.

gpx_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

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.

Run: flutter pub get

Configure the native parts:

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:

1    allprojects {
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 project pathname

 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}

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

platform :ios, '14.0'

We recommend you to run these commands after you copy the gem_kit into your project: |flutter clean |flutter pub get |and |cd ios |pod install

Then run the project:

flutter run --debug
or
flutter run --release

How It Works

gpx_route - example flutter screenshot

The following code demonstrates the main components of the GPX route example:

import 'package:gem_kit/core.dart';
import 'package:gem_kit/map.dart';
import 'package:gem_kit/navigation.dart';
import 'package:gem_kit/routing.dart';
import 'package:path_provider/path_provider.dart';
import 'package:flutter/material.dart' hide Route;
import 'package:flutter/services.dart';
import 'dart:async';
import 'dart:io';

Future<void> main() async {
  const projectApiToken = String.fromEnvironment('GEM_TOKEN');
  await GemKit.initialize(appAuthorization: projectApiToken);
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'GPX Route',
      home: MyHomePage(),
    );
  }
}

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:

void _onMapCreated(GemMapController controller) {
  // Save controller for further usage.
  _mapController = controller;
}

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:

Future<void> _copyGpxToAppDocsDir() async {
  final docDirectory = await getApplicationDocumentsDirectory();
  final gpxFile = File('${docDirectory.path}/recorded_route.gpx');
  final imageBytes = await rootBundle.load('assets/recorded_route.gpx');
  final buffer = imageBytes.buffer;
  await gpxFile.writeAsBytes(
    buffer.asUint8List(imageBytes.offsetInBytes, imageBytes.lengthInBytes),
  );
}

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:

Future<void> _importGPX() async {
  _showSnackBar(context, message: 'The route is calculating.');

  final docDirectory = await getApplicationDocumentsDirectory();
  final gpxFile = File('${docDirectory.path}/recorded_route.gpx');

  if (!await gpxFile.exists()) {
    print('GPX file does not exist (${gpxFile.path})');
    return;
  }

  final bytes = await gpxFile.readAsBytes();
  final pathData = Uint8List.fromList(bytes);
  final gemPath = Path.create(data: pathData, format: 0);
  final landmarkList = gemPath.toLandmarkList();

  print("GPX Landmarklist size: ${landmarkList.length}");

  final routePreferences =
      RoutePreferences(transportMode: RouteTransportMode.bicycle);

  RoutingService.calculateRoute(
    landmarkList,
    routePreferences,
    (err, routes) {
      ScaffoldMessenger.of(context).clearSnackBars();

      if (err == GemError.success) {
        final routesMap = _mapController.preferences.routes;

        for (final route in routes!) {
          routesMap.add(route, route == routes.first, label: route.getMapLabel());
        }

        _mapController.centerOnRoutes(routes: routes);

        setState(() {
          _areRoutesBuilt = true;
        });
      }
    },
  );
  _isGpxDataLoaded = true;
}
When the “Calculate Route” button is pressed, this function reads the GPX file from the app’s documents directory and calculates a route based on the landmarks (waypoints) extracted from the GPX data.
The routes are displayed on the map and the camera is centered to ensure all routes fit within the viewport.

Starting and Stopping the Simulation

gpx_route - example flutter screenshot

The simulation can be started or stopped using the following functions:

void _startSimulation() {
  if (_isSimulationActive) return;
  if (!_isGpxDataLoaded) return;

  final routes = _mapController.preferences.routes;

  _navigationHandler = NavigationService.startSimulation(
    routes.mainRoute,
    (eventType, instruction) {
      // Navigation instruction callback.
    },
    speedMultiplier: 2,
  );

  _mapController.startFollowingPosition();

  setState(() => _isSimulationActive = true);
}

void _stopSimulation() {
  _mapController.preferences.routes.clear();

  setState(() => _areRoutesBuilt = false);

  if (_isSimulationActive) {
    NavigationService.cancelNavigation(_navigationHandler!);
    _navigationHandler = null;

    setState(() => _isSimulationActive = false);
  }
}
The _startSimulation function initiates the navigation simulation along the main route, with the camera following the simulated position. The _stopSimulation function stops the simulation and clears the routes from the map.

Utility Functions

Utility functions are also included to display messages and format route labels:

void _showSnackBar(BuildContext context,
    {required String message, Duration duration = const Duration(hours: 1)}) {
  final snackBar = SnackBar(
    content: Text(message),
    duration: duration,
  );

  ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
extension RouteExtension on Route {
  String getMapLabel() {
    final totalDistance = getTimeDistance().unrestrictedDistanceM +
        getTimeDistance().restrictedDistanceM;
    final totalDuration =
        getTimeDistance().unrestrictedTimeS + getTimeDistance().restrictedTimeS;

    return '${_convertDistance(totalDistance)} \n${_convertDuration(totalDuration)}';
  }

  String _convertDistance(int meters) {
    if (meters >= 1000) {
      double kilometers = meters / 1000;
      return '${kilometers.toStringAsFixed(1)} km';
    } else {
      return '${meters.toString()} m';
    }
  }

  String _convertDuration(int seconds) {
    int hours = seconds ~/ 3600;
    int minutes = (seconds % 3600) ~/ 60;

    String hoursText = (hours > 0) ? '$hours h ' : '';
    String minutesText = '$minutes min';

    return hoursText + minutesText;
  }
}

The _showSnackBar method displays messages during route calculation. The RouteExtension is an extension that formats route labels to display the total distance and duration.

Flutter Examples

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