Route Profile¶
In this guide you will learn how to display a map, calculate routes between multiple points, and show a detailed route profile.
Setup¶
Prerequisites¶
Build and Run¶
Start a terminal/command prompt and navigate to the route_profile
directory within the Flutter examples directory. This is the name of the 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:
allprojects {
repositories {
google()
mavenCentral()
maven {
url "${rootDir}/../plugins/gem_kit/android/build"
}
}
}
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
android {
defaultConfig {
applicationId "com.magiclane.gem_kit.examples.example_pathname"
minSdk 21
targetSdk flutter.targetSdk
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
}
buildTypes {
release {
minifyEnabled false
shrinkResources false
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug
}
}
}
Then run the project:
flutter run --debug
orflutter run --release
Import Necessary Packages¶
First, import the required packages in your Dart code.
import 'package:gem_kit/core.dart';
import 'package:gem_kit/map.dart';
import 'package:gem_kit/routing.dart';
import 'package:flutter/material.dart' hide Route;
import 'elevation_chart.dart';
import 'route_profile_panel.dart';
App entry and initialization¶
const projectApiToken = String.fromEnvironment('GEM_TOKEN');
void main() {
runApp(const MyApp());
}
This code initializes the projectApiToken with the required authorization token and launches the app.
How it Works¶
This example demonstrates the following key features:
Calculates routes and renders them on the map.
Display detailed route profile, including an elevation chart that visualizes the terrain along the route.
Build the Main Application¶
Define the main application widget, MyApp.
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Route Profile',
home: MyHomePage(),
);
}
}
Handle Maps and Routes in the Stateful Widget¶
Create the stateful widget, MyHomePage, which will handle the map and routing functionality.
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
Define State Variables and Methods¶
Within _MyHomePageState
, define the necessary state variables and methods to interact with the map and manage routes.
class _MyHomePageState extends State<MyHomePage> {
late GemMapController _mapController;
TaskHandler? _routingHandler;
Route? _focusedRoute;
final LineAreaChartController _chartController = LineAreaChartController();
@override
void dispose() {
GemKit.release();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.deepPurple[900],
title: const Text('Route Profile', style: TextStyle(color: Colors.white)),
actions: [
if (_routingHandler == null && _focusedRoute == null)
IconButton(
onPressed: () => _onBuildRouteButtonPressed(context),
icon: const Icon(Icons.route, color: Colors.white),
),
if (_routingHandler != null)
IconButton(
onPressed: () => _onCancelRouteButtonPressed(),
icon: const Icon(Icons.stop, color: Colors.white),
),
if (_focusedRoute != null)
IconButton(
onPressed: () => _onClearRoutesButtonPressed(),
icon: const Icon(Icons.clear, color: Colors.white),
),
],
),
body: Stack(
children: [
GemMap(
onMapCreated: _onMapCreated,
),
if (_focusedRoute != null)
Align(
alignment: Alignment.bottomCenter,
child: RouteProfilePanel(
route: _focusedRoute!,
mapController: _mapController,
chartController: _chartController,
centerOnRoute: () => _centerOnRoute([_focusedRoute!]),
))
],
),
);
}
void _onMapCreated(GemMapController controller) {
_mapController = controller;
_registerRouteTapCallback();
}
void _onBuildRouteButtonPressed(BuildContext context) {
final departureLandmark =
Landmark.withLatLng(latitude: 46.59344, longitude: 7.91069);
final destinationLandmark =
Landmark.withLatLng(latitude: 46.55945, longitude: 7.89293);
final routePreferences = RoutePreferences(
buildTerrainProfile: const BuildTerrainProfile(enable: true),
transportMode: RouteTransportMode.pedestrian);
_showSnackBar(context, message: "The route is being calculated.");
_routingHandler = RoutingService.calculateRoute(
[departureLandmark, destinationLandmark], routePreferences,
(err, routes) {
_routingHandler = null;
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());
}
_centerOnRoute(routes);
setState(() {
_focusedRoute = routes.first;
});
}
});
setState(() {});
}
void _onClearRoutesButtonPressed() {
_mapController.deactivateAllHighlights();
_mapController.preferences.routes.clear();
setState(() {
_focusedRoute = null;
});
}
void _onCancelRouteButtonPressed() {
if (_routingHandler != null) {
RoutingService.cancelRoute(_routingHandler!);
setState(() {
_routingHandler = null;
});
}
}
void _registerRouteTapCallback() {
_mapController.registerTouchCallback((pos) async {
_mapController.setCursorScreenPosition(pos);
final routes = _mapController.cursorSelectionRoutes();
if (routes.isNotEmpty) {
_mapController.preferences.routes.mainRoute = routes.first;
if (_chartController.setCurrentHighlight != null) {
_chartController.setCurrentHighlight!(0);
}
setState(() {
_focusedRoute = routes.first;
});
_centerOnRoute([_focusedRoute!]);
}
});
}
void _centerOnRoute(List<Route> route) {
const appbarHeight = 50;
const padding = 20;
_mapController.centerOnRoutes(route,
screenRect: RectType(
x: 0,
y: (appbarHeight + padding * MediaQuery.of(context).devicePixelRatio)
.toInt(),
width: (MediaQuery.of(context).size.width *
MediaQuery.of(context).devicePixelRatio)
.toInt(),
height: ((MediaQuery.of(context).size.height / 2 -
appbarHeight -
2 * padding * MediaQuery.of(context).devicePixelRatio) *
MediaQuery.of(context).devicePixelRatio)
.toInt(),
));
}
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);
}
}
This example guides you through the setup and implementation of a route profile in a Flutter application using the ``gem_kit``package. The focus is on handling maps, user interactions, and route preferences to provide a seamless user experience for calculating and displaying route profiles.