Route Alarms
This example demonstrates how to build a Flutter app using the Maps SDK to calculate and navigate a route containing a speed limit overlay and receive notifications.
How It Works
The example app highlights the following features:
- Calculate a route.
- Simulate navigation on a route.
- Register a listener to receive alarm notifications.
![]() | ![]() |
---|---|
Initial screen | Displaying a screenshot of the computed route |
UI and Map Integration
The following code builds the UI with a GemMap
widget and an app bar that includes buttons for computing and navigating a route. When the simulated position tracker gets within 500m proximity of the speed limit overlay, an alarm notification is triggered and displayed on the screen.
const projectApiToken = String.fromEnvironment('GEM_TOKEN');
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Route Alarms',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late GemMapController _mapController;
bool _areRoutesBuilt = false;
bool _isSimulationActive = false;
// We use the progress listener to cancel the route calculation.
TaskHandler? _routingHandler;
// We use the progress listener to cancel the navigation.
TaskHandler? _navigationHandler;
AlarmService? _alarmService;
AlarmListener? _alarmListener;
// The closest alarm and its associated distance and image
OverlayItemPosition? _closestOverlayItem;
void dispose() {
GemKit.release();
super.dispose();
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
"Route Alarms",
style: TextStyle(color: Colors.white),
),
backgroundColor: Colors.deepPurple[900],
actions: [
if (!_isSimulationActive && _areRoutesBuilt)
IconButton(
onPressed: _startSimulation,
icon: const Icon(Icons.play_arrow, color: Colors.white),
),
if (_isSimulationActive)
IconButton(
onPressed: _stopSimulation,
icon: const Icon(Icons.stop, color: Colors.white),
),
if (!_areRoutesBuilt)
IconButton(
onPressed: () => _onBuildRouteButtonPressed(context),
icon: const Icon(Icons.route, color: Colors.white),
),
],
),
body: Stack(
children: [
GemMap(
key: ValueKey("GemMap"),
onMapCreated: _onMapCreated,
appAuthorization: projectApiToken,
),
if (_closestOverlayItem != null)
Positioned(
bottom: MediaQuery.of(context).padding.bottom + 10,
left: 0,
child: BottomAlarmPanel(
remainingDistance: _closestOverlayItem!.distance.toString(),
image:
_closestOverlayItem!.overlayItem.img.isValid
? _closestOverlayItem!.overlayItem.img
.getRenderableImageBytes()
: null,
),
),
],
),
resizeToAvoidBottomInset: false,
);
}
void _onMapCreated(GemMapController controller) {
_mapController = controller;
}
// Custom method for calling calculate route and displaying the results.
void _onBuildRouteButtonPressed(BuildContext context) {
// Define the departure.
final departureLandmark = Landmark.withLatLng(
latitude: 50.92899490001731,
longitude: 9.544136681645025,
);
// Define the destination.
final destinationLandmark = Landmark.withLatLng(
latitude: 50.919902402432946,
longitude: 9.55855522546262,
);
// Define the route preferences.
final routePreferences = RoutePreferences();
_showSnackBar(context, message: 'The route is calculating.');
// Calling the calculateRoute SDK method.
// (err, results) - is a callback function that gets called when the route computing is finished.
// err is an error enum, results is a list of routes.
_routingHandler = RoutingService.calculateRoute(
[departureLandmark, destinationLandmark],
routePreferences,
(err, routes) async {
// If the route calculation is finished, we don't have a progress listener anymore.
_routingHandler = null;
ScaffoldMessenger.of(context).clearSnackBars();
// If there aren't any errors, we display the routes.
if (err == GemError.success) {
// Get the routes collection from map preferences.
final routesMap = _mapController.preferences.routes;
// Display the routes on map.
for (final route in routes) {
routesMap.add(route, route == routes.first);
}
// Center the camera on routes.
_mapController.centerOnRoutes(routes: routes);
}
setState(() {
_areRoutesBuilt = true;
});
},
);
}
// Method for starting the simulation and following the position,
void _startSimulation() {
final routes = _mapController.preferences.routes;
_mapController.preferences.routes.clearAllButMainRoute();
if (routes.mainRoute == null) {
_showSnackBar(context, message: "No main route available");
return;
}
_alarmListener = AlarmListener(
onOverlayItemAlarmsUpdated: () {
// The overlay item alarm list containing the overlay items that are to be intercepted
OverlayItemAlarmsList overlayItemAlarms =
_alarmService!.overlayItemAlarms;
// The overlay items and their distance from the reference position
// Sorted ascending by distance from the current position
List<OverlayItemPosition> items = overlayItemAlarms.items;
if (items.isEmpty) {
return;
}
// The closest overlay item and its associated distance
OverlayItemPosition closestOverlayItem = items.first;
setState(() {
_closestOverlayItem = closestOverlayItem;
});
},
// When the overlay item alarms are passed over
onOverlayItemAlarmsPassedOver: () {
setState(() {
_closestOverlayItem = null;
});
},
);
// Set the alarms service with the listener
_alarmService = AlarmService(_alarmListener!);
_alarmService!.alarmDistance = 500;
// Add the social reports overlay to be tracked by the alarm service
_alarmService!.overlays.add(CommonOverlayId.safety.id);
_navigationHandler = NavigationService.startSimulation(
routes.mainRoute!,
null,
onNavigationInstruction: (instruction, events) {
setState(() {
_isSimulationActive = true;
});
},
onDestinationReached: (landmark) {
_stopSimulation();
_cancelRoute();
},
onError: (error) {
// If the navigation has ended or if an error occurred while navigating, remove routes and reset the closest alarm.
setState(() {
_isSimulationActive = false;
_closestOverlayItem = null;
_cancelRoute();
});
if (error != GemError.cancel) {
_stopSimulation();
}
return;
},
);
// Set the camera to follow position.
_mapController.startFollowingPosition();
}
// Method for removing the routes from display,
void _cancelRoute() {
// Remove the routes from map.
_mapController.preferences.routes.clear();
if (_routingHandler != null) {
// Cancel the navigation.
RoutingService.cancelRoute(_routingHandler!);
_routingHandler = null;
}
setState(() {
_areRoutesBuilt = false;
});
}
// Method to stop the simulation and remove the displayed routes,
void _stopSimulation() {
// Cancel the navigation.
NavigationService.cancelNavigation(_navigationHandler!);
_navigationHandler = null;
_cancelRoute();
setState(() => _isSimulationActive = false);
}
// Method to show a message in case the calculate route is not finished,
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);
}
}
Flutter Examples
Maps SDK for Flutter Examples can be downloaded or cloned with Git.