Speed Watcher¶
Setup¶
Prerequisites¶
Build and Run¶
Go to the speed_watcher
directory within the Flutter examples directory.
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}
Then run the project:
flutter run --debug
orflutter run --release
How It Works¶
This example demonstrates how to monitor speed while navigating using the ``gem_kit``package.
Import Necessary Packages¶
Start by importing the required packages.
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:flutter/material.dart';
Initialize GemKit¶
In the main
function, initialize GemKit with your project API token.
1Future<void> main() async {
2 const projectApiToken = String.fromEnvironment('GEM_TOKEN');
3 await GemKit.initialize(appAuthorization: projectApiToken);
4 runApp(const MyApp());
5}
Build the Main Application¶
Define the main application widget, MyApp
.
1class MyApp extends StatelessWidget {
2 const MyApp({super.key});
3
4 @override
5 Widget build(BuildContext context) {
6 return const MaterialApp(
7 debugShowCheckedModeBanner: false,
8 title: 'Speed Watcher',
9 home: MyHomePage(),
10 );
11 }
12}
Handle Map and Route Functionality¶
Create the stateful widget, MyHomePage
, which will handle the map and routing functionality.
1class MyHomePage extends StatefulWidget {
2 const MyHomePage({super.key});
3
4 @override
5 State<MyHomePage> createState() => _MyHomePageState();
6}
Define State Variables and Methods¶
Within _MyHomePageState
, define the necessary state variables and methods to manage the map and navigation.
1class _MyHomePageState extends State<MyHomePage> {
2 late GemMapController _mapController;
3 late NavigationInstruction currentInstruction;
4
5 bool _areRoutesBuilt = false;
6 bool _isSimulationActive = false;
7
8 TaskHandler? _routingHandler;
9 TaskHandler? _navigationHandler;
10
11 @override
12 void dispose() {
13 GemKit.release();
14 super.dispose();
15 }
16
17 @override
18 Widget build(BuildContext context) {
19 return Scaffold(
20 appBar: AppBar(
21 title: const Text("Speed Watcher", style: TextStyle(color: Colors.white)),
22 backgroundColor: Colors.deepPurple[900],
23 actions: [
24 if (!_isSimulationActive && _areRoutesBuilt)
25 IconButton(
26 onPressed: _startSimulation,
27 icon: const Icon(Icons.play_arrow, color: Colors.white),
28 ),
29 if (_isSimulationActive)
30 IconButton(
31 onPressed: _stopSimulation,
32 icon: const Icon(Icons.stop, color: Colors.white),
33 ),
34 if (!_areRoutesBuilt)
35 IconButton(
36 onPressed: () => _onBuildRouteButtonPressed(context),
37 icon: const Icon(Icons.route, color: Colors.white),
38 ),
39 ],
40 ),
41 body: Stack(children: [
42 GemMap(onMapCreated: _onMapCreated),
43 if (_isSimulationActive) const Align(alignment: Alignment.topCenter, child: SpeedIndicator()),
44 if (_isSimulationActive) Align(alignment: Alignment.bottomCenter, child: FollowPositionButton(onTap: () => _mapController.startFollowingPosition())),
45 ]),
46 resizeToAvoidBottomInset: false,
47 );
48 }
49
50 void _onMapCreated(GemMapController controller) {
51 _mapController = controller;
52 }
Custom Method for Building the Route¶
Define a method for building the route based on the departure and destination landmarks.
1void _onBuildRouteButtonPressed(BuildContext context) {
2 final departureLandmark = Landmark.withLatLng(latitude: 41.898499, longitude: 12.526655);
3 final destinationLandmark = Landmark.withLatLng(latitude: 41.891037, longitude: 12.492692);
4 final routePreferences = RoutePreferences();
5 _showSnackBar(context, message: 'The route is calculating.');
6
7 _routingHandler = RoutingService.calculateRoute(
8 [departureLandmark, destinationLandmark], routePreferences,
9 (err, routes) {
10 ScaffoldMessenger.of(context).clearSnackBars();
11
12 if (err == GemError.success) {
13 final routesMap = _mapController.preferences.routes;
14 for (final route in routes!) {
15 routesMap.add(route, route == routes.first, label: route.getMapLabel());
16 }
17 _mapController.centerOnRoutes(routes);
18 }
19 setState(() {
20 _areRoutesBuilt = true;
21 });
22 });
23}
Starting the Simulation¶
Define the method for starting the navigation simulation.
1void _startSimulation() {
2 final routes = _mapController.preferences.routes;
3
4 _navigationHandler = NavigationService.startSimulation(routes.mainRoute,
5 (type, instruction) {
6 if (type == NavigationEventType.destinationReached || type == NavigationEventType.error) {
7 setState(() {
8 _isSimulationActive = false;
9 _cancelRoute();
10 });
11 return;
12 }
13 _isSimulationActive = true;
14
15 if (instruction != null) {
16 setState(() => currentInstruction = instruction);
17 }
18 });
19
20 _mapController.startFollowingPosition(); // Follow position during navigation
21}
Stopping the Simulation¶
Define the method for stopping the navigation simulation.
1void _stopSimulation() {
2 NavigationService.cancelNavigation(_navigationHandler!);
3 _navigationHandler = null;
4
5 _cancelRoute();
6
7 setState(() => _isSimulationActive = false);
8}
Canceling the Route¶
Define the method for canceling the route.
1void _cancelRoute() {
2 _mapController.preferences.routes.clear();
3
4 if (_routingHandler != null) {
5 RoutingService.cancelRoute(_routingHandler!);
6 _routingHandler = null;
7 }
8
9 setState(() {
10 _areRoutesBuilt = false;
11 });
12}
Showing Snack Bars¶
Define the method for displaying snack bars with messages.
1void _showSnackBar(BuildContext context, {required String message, Duration duration = const Duration(hours: 1)}) {
2 final snackBar = SnackBar(content: Text(message), duration: duration);
3 ScaffoldMessenger.of(context).showSnackBar(snackBar);
4}