================ LIBRARY RULES ================ - This project uses: flutter, dart, sdk ================ CODE SNIPPETS ================ TITLE: Start Simulation and Handle Updates DESCRIPTION: Demonstrates how to start a navigation simulation with a custom callback for instruction updates and how to handle different update events. It also shows how to add a route to preferences and start following the device's position. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/docs/8_navigation/01_get-started-navigation.md#_snippet_3 LANGUAGE: dart CODE: ``` void simulationInstructionUpdated(NavigationInstruction instruction, Set events) { for (final event in events) { switch (event) { case NavigationInstructionUpdateEvents.nextTurnUpdated: showSnackbar("Turn updated"); break; case NavigationInstructionUpdateEvents.nextTurnImageUpdated: showSnackbar("Turn image updated"); break; case NavigationInstructionUpdateEvents.laneInfoUpdated: showSnackbar("Lane info updated"); break; } } final instructionText = instruction.nextTurnInstruction; // handle instruction } mapController.preferences.routes.add(route, true); TaskHandler? taskHandler = NavigationService.startSimulation( route, null, onNavigationInstruction: simulationInstructionUpdated, speedMultiplier: 2, ); //highlight-start // [Optional] Set the camera to follow position. // Usually we want this when in navigation mode mapController.startFollowingPosition(); // At any moment, we can cancel the navigation // NavigationService.cancelNavigation(taskHandler); //highlight-end ``` -------------------------------- TITLE: Display a Map View in Flutter DESCRIPTION: Demonstrates the basic setup for displaying a map in a Flutter application. It includes importing necessary packages, defining the main application structure, and rendering the GemMap widget with an authorization token and an initialization callback. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/docs/4_maps/01_get-started.md#_snippet_0 LANGUAGE: dart CODE: ``` import 'package:flutter/material.dart'; import 'package:gem_kit/core.dart'; import 'package:gem_kit/map.dart'; const projectApiToken = String.fromEnvironment('GEM_TOKEN'); void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( debugShowCheckedModeBanner: false, title: 'Hello Map', home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @override State createState() => _MyHomePageState(); } class _MyHomePageState extends State { @override void dispose() { GemKit.release(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.deepPurple[900], title: const Text('Hello Map', style: TextStyle(color: Colors.white)), ), body: const GemMap( appAuthorization: projectApiToken, onMapCreated: _onMapCreated, ), ); } void _onMapCreated(GemMapController mapController) { // Code executed when the map is initialized } } ``` -------------------------------- TITLE: Basic Flutter App Setup with GemMap DESCRIPTION: Sets up a basic Flutter application with a Scaffold, AppBar, and the GemMap widget. It includes initialization logic for the map controller and registers a touch callback. The app bar features a button to start route simulation. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/examples/17_routing-navigation/25_social-event-voting.md#_snippet_0 LANGUAGE: dart CODE: ``` const projectApiToken = String.fromEnvironment('GEM_TOKEN'); void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( title: 'Social Event Voting', debugShowCheckedModeBanner: false, home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @override State createState() => _MyHomePageState(); } class _MyHomePageState extends State { late GemMapController _mapController; AlarmService? _alarmService; AlarmListener? _alarmListener; OverlayItemPosition? _closestOverlayItem; TaskHandler? _navigationHandler; @override void dispose() { GemKit.release(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.deepPurple[900], title: const Text( 'Social Event Voting', style: TextStyle(color: Colors.white), ), actions: [ if (_navigationHandler == null) IconButton( onPressed: _startSimulation, icon: Icon(Icons.route, color: Colors.white), ), ], ), body: Stack( children: [ GemMap( key: ValueKey("GemMap"), onMapCreated: _onMapCreated, appAuthorization: projectApiToken, ), if (_closestOverlayItem != null) Padding( padding: const EdgeInsets.all(8.0), child: Align( alignment: Alignment.bottomCenter, child: SocialEventPanel( overlayItem: _closestOverlayItem!.overlayItem, onClose: () { setState(() { _closestOverlayItem = null; }); }, ), ), ), ], ), ); } void _onMapCreated(GemMapController controller) async { _mapController = controller; _mapController.registerTouchCallback((point) { _mapController.setCursorScreenPosition(point); }); _registerSocialEventListener(); } Future _onBuildRouteButtonPressed(BuildContext context) async { Route? routeWithReport = await _getRouteWithReport(); if (routeWithReport != null) { _mapController.preferences.routes.add( routeWithReport, true, routeRenderSettings: RouteRenderSettings( options: { RouteRenderOptions.showTraffic, RouteRenderOptions.showHighlights, }, ), ); } else { _showSnackBar(context, message: "No route available"); } } Future _startSimulation() async { await _onBuildRouteButtonPressed(context); final routes = _mapController.preferences.routes; if (routes.mainRoute == null) { _showSnackBar(context, message: "No main route available"); return; } _navigationHandler = NavigationService.startSimulation( routes.mainRoute!, null, onNavigationInstruction: (instruction, events) {}, onDestinationReached: (landmark) => _stopSimulation(), ); _mapController.startFollowingPosition(); } void _stopSimulation() { if (_navigationHandler != null) { NavigationService.cancelNavigation(_navigationHandler!); } setState(() { _navigationHandler = null; }); _navigationHandler = null; _cancelRoute(); } void _cancelRoute() { _mapController.preferences.routes.clear(); } void _registerSocialEventListener() { _alarmListener = AlarmListener( onOverlayItemAlarmsUpdated: () { OverlayItemAlarmsList overlayItemAlarms = _alarmService!.overlayItemAlarms; ``` -------------------------------- TITLE: Navigation Modes DESCRIPTION: Explains the two primary methods for navigating a route within the Maps SDK for Flutter: Navigation mode using PositionService and Simulation mode for testing. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/docs/8_navigation/01_get-started-navigation.md#_snippet_0 LANGUAGE: flutter CODE: ``` To enable navigation, the first step is to compute a valid, navigable route (note that non-navigable routes, such as range routes, are not supported). The SDK offers two methods for navigating a route: - **Navigation:** This method relies on the position data provided by the PositionService to guide the user along the route. - **Simulation:** This method does not require user-provided position data. Instead, it simulates the navigation instructions that would be delivered to the user, allowing developers to test and preview the experience without needing an actual position. ``` -------------------------------- TITLE: Flutter App UI Setup DESCRIPTION: Sets up the basic structure of a Flutter application, including the MaterialApp and Scaffold, with an AppBar and the GemMap widget. This snippet defines the main UI components for the 'Follow Position' example. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/examples/17_maps-3dscene-examples/08_follow-position.md#_snippet_0 LANGUAGE: dart CODE: ``` class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( debugShowCheckedModeBanner: false, title: 'Follow Position', home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @override State createState() => _MyHomePageState(); } class _MyHomePageState extends State { late GemMapController _mapController; PermissionStatus _locationPermissionStatus = PermissionStatus.denied; bool _hasLiveDataSource = false; @override void dispose() { GemKit.release(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.deepPurple[900], title: const Text('Follow Position', style: TextStyle(color: Colors.white)), actions: [ IconButton( onPressed: _onFollowPositionButtonPressed, icon: const Icon(Icons.location_searching_sharp, color: Colors.white), ), ], ), body: GemMap( key: ValueKey("GemMap"), onMapCreated: _onMapCreated, appAuthorization: projectApiToken, ), ); } } ``` -------------------------------- TITLE: startNavigation Implementation Example DESCRIPTION: An example of how the startNavigation function is implemented, including error handling for API calls and registration of navigation listeners. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/api-references/2.24.0/navigation/NavigationService/startNavigation.html#_snippet_3 LANGUAGE: dart CODE: ``` static TaskHandler? startNavigation( final Route route, @Deprecated( 'Use onNavigationInstruction, onDestinationReached and onError instead', ) final void Function( NavigationEventType eventType, NavigationInstruction? instruction, )? onNavigationInstructionUpdate, { final void Function( NavigationInstruction instruction, Set events, )? onNavigationInstruction, final void Function()? onNavigationStarted, final void Function(String textInstruction)? onTextToSpeechInstruction, final void Function(Landmark landmark)? onWaypointReached, final void Function(Landmark landmark)? onDestinationReached, final void Function(Route route)? onRouteUpdated, final void Function(Route route, int travelTime, int delay, int timeGain)? onBetterRouteDetected, final void Function(GemError reason)? onBetterRouteRejected, final void Function()? onBetterRouteInvalidated, final void Function()? onSkipNextIntermediateDestinationDetected, final void Function()? onTurnAround, final void Function(GemError error)? onError, final void Function(NavigationStatus status)? onNotifyStatusChange, @Deprecated( 'Use SoundPlayingService.canPlaySounds instead', ) final bool? autoPlaySound, }) { final OperationResult result = staticMethod( 'NavigationService', 'startNavigation', args: {'route': route.pointerId, 'simulation': false}, ); final int gemApiError = result['gemApiError']; if (GemErrorExtension.isErrorCode(gemApiError)) { final GemError errorCode = GemErrorExtension.fromCode(gemApiError); onError?.call(errorCode); return null; } if (autoPlaySound != null) { SoundPlayingService.canPlaySounds = autoPlaySound; } final int listenerId = result['result']; final NavigationListener listener = NavigationListener.init(listenerId); listener.registerAll( onNavigationStarted: onNavigationStarted, onNavigationInstructionUpdated: ( final NavigationInstruction instruction, final Set events, ) { onNavigationInstructionUpdate?.call( NavigationEventType.navigationInstructionUpdate, instruction, ); onNavigationInstruction?.call(instruction, events); }, onWaypointReached: onWaypointReached, onDestinationReached: (final Landmark destination) { onNavigationInstructionUpdate?.call( NavigationEventType.destinationReached, null, ); onDestinationReached?.call(destination); }, onNavigationError: (final GemError error) { ``` -------------------------------- TITLE: Navigation Event Callbacks DESCRIPTION: This snippet demonstrates how to register various navigation event callbacks when initiating navigation. It includes handlers for instructions, route updates, destination reached, and more. These callbacks allow for real-time updates and custom logic during the navigation process. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/docs/8_navigation/01_get-started-navigation.md#_snippet_4 LANGUAGE: dart CODE: ``` void onNavigationInstruction(NavigationInstruction navigationInstruction, Set events) {} void onNavigationStarted() {} void onTextToSpeechInstruction(String text) {} void onWaypointReached(Landmark landmark) {} void onDestinationReached(Landmark landmark) {} void onRouteUpdated(Route route) {} void onBetterRouteDetected( Route route, int travelTime, int delay, int timeGain) {} void onBetterRouteRejected(GemError error) {} void onBetterRouteInvalidated() {} void onSkipNextIntermediateDestinationDetected() {} void onTurnAround() {} TaskHandler? taskHandler = NavigationService.startNavigation( route, null, onNavigationInstruction: onNavigationInstruction, onNavigationStarted: onNavigationStarted, onTextToSpeechInstruction: onTextToSpeechInstruction, onWaypointReached: onWaypointReached, onDestinationReached: onDestinationReached, onRouteUpdated: onRouteUpdated, onBetterRouteDetected: onBetterRouteDetected, onBetterRouteRejected: onBetterRouteRejected, onBetterRouteInvalidated: onBetterRouteInvalidated, onSkipNextIntermediateDestinationDetected: onSkipNextIntermediateDestinationDetected, onTurnAround: onTurnAround, ); ``` -------------------------------- TITLE: Requesting Location Permissions with permission_handler DESCRIPTION: Demonstrates how to use the `permission_handler` package in Dart to request location permissions from the user and set the live data source if granted. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/docs/5_positioning/01_get-started-positioning.md#_snippet_2 LANGUAGE: dart CODE: ``` // For Android & iOS platforms, permission_handler package is used to ask for permissions. final locationPermissionStatus = await Permission.locationWhenInUse.request(); if (locationPermissionStatus == PermissionStatus.granted) { // After the permission was granted, we can set the live data source (in most cases the GPS). // The data source should be set only once, otherwise we'll get GemError.exist error. GemError setLiveDataSourceError = PositionService.instance.setLiveDataSource(); showSnackbar("Set live datasource with result: $setLiveDataSourceError"); } if (locationPermissionStatus == PermissionStatus.denied) { // The user denied the permission showSnackbar("Location permission denied"); } if (locationPermissionStatus == PermissionStatus.permanentlyDenied) { // The user permanently denied the permission // The user should go to the app settings to enable the permission showSnackbar("Location permission permanently denied"); } ``` -------------------------------- TITLE: Start Navigation and Handle Updates DESCRIPTION: Initiates navigation with a computed route and defines callback functions to handle navigation instruction updates, destination reached, and errors. The `startNavigation` method returns a `TaskHandler` which can be used to cancel the navigation. It's recommended to set the map controller to follow the position during navigation. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/docs/8_navigation/01_get-started-navigation.md#_snippet_2 LANGUAGE: dart CODE: ``` void navigationInstructionUpdated(NavigationInstruction instruction, Set events) { for (final event in events) { switch (event) { case NavigationInstructionUpdateEvents.nextTurnUpdated: showSnackbar("Turn updated"); break; case NavigationInstructionUpdateEvents.nextTurnImageUpdated: showSnackbar("Turn image updated"); break; case NavigationInstructionUpdateEvents.laneInfoUpdated: showSnackbar("Lane info updated"); break; } } final instructionText = instruction.nextTurnInstruction; // handle instruction } void onDestinationReached(Landmark destination) { // handle destination reached } void onError(GemError err) { // handle error } //highlight-start TaskHandler? handler = NavigationService.startNavigation(route, null, onNavigationInstruction: navigationInstructionUpdated, onDestinationReached: onDestinationReached, onError: onError); //highlight-end // [Optional] Set the camera to follow position. // Usually we want this when in navigation mode mapController.startFollowingPosition(); // At any moment, we can cancel the navigation // NavigationService.cancelNavigation(taskHandler); ``` -------------------------------- TITLE: Configure AlarmService and AlarmListener DESCRIPTION: This snippet demonstrates how to create an AlarmListener with various callback methods for different alarm events and then instantiate an AlarmService using this listener. It highlights the importance of keeping these objects in memory for notifications to function correctly. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/docs/9_alarms/01_get-started-alarms.md#_snippet_0 LANGUAGE: dart CODE: ``` AlarmListener alarmListener = AlarmListener( onBoundaryCrossed: (entered, exited) {}, onMonitoringStateChanged: (isMonitoringActive) {}, onTunnelEntered: () {}, onTunnelLeft: () {}, onLandmarkAlarmsUpdated: () {}, onOverlayItemAlarmsUpdated: () {}, onLandmarkAlarmsPassedOver: () {}, onOverlayItemAlarmsPassedOver: () {}, onHighSpeed: (limit, insideCityArea) {}, onSpeedLimit: (speed, limit, insideCityArea) {}, onNormalSpeed: (limit, insideCityArea) {}, onEnterDayMode: () {}, onEnterNightMode: () {}, ); AlarmService alarmService = AlarmService(alarmListener); ``` -------------------------------- TITLE: Main App Setup DESCRIPTION: Sets up the main MaterialApp and MyHomePage for the Flutter application. This includes basic app configuration and navigation. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/examples/17_maps-3dscene-examples/05_map-gestures.md#_snippet_0 LANGUAGE: dart CODE: ``` class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( debugShowCheckedModeBanner: false, title: 'Map Gestures', home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @override State createState() => _MyHomePageState(); } ``` -------------------------------- TITLE: GemMap Widget Initialization Callback DESCRIPTION: Highlights the `onMapCreated` callback of the `GemMap` widget, which is invoked upon map initialization. This callback provides a `GemMapController` instance for further map interactions and customization. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/docs/4_maps/01_get-started.md#_snippet_1 LANGUAGE: dart CODE: ``` const GemMap( appAuthorization: projectApiToken, //highlight-start onMapCreated: _onMapCreated, //highlight-end ), ``` -------------------------------- TITLE: PositionService Data Sources DESCRIPTION: Details the data sources that can be used by the PositionService for navigation, including real GPS data and custom position data. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/docs/8_navigation/01_get-started-navigation.md#_snippet_1 LANGUAGE: flutter CODE: ``` If we are in navigation mode, the position is provided by `PositionService`.It can use: - **Real GPS Data:** When ``PositionService.instance.setLiveDataSource`` is called, the service will use real-time GPS data to provide position updates. This requires the appropriate application permissions, which differ between Android and iOS. Additionally, the application must programmatically request these permissions from the user. - **Custom Position Data:** In this mode, a custom data source can be configured to supply position updates. No permissions are required in this case, as the positions are provided through the custom source rather than the device's GPS. If you want to use a custom position take a look at [Custom positioning](/guides/positioning/custom-positioning). Currently, only one of navigation and simulation can be active at a time, regardless of the number of maps present within the application. ``` -------------------------------- TITLE: Start and Stop Driver Behaviour Analysis DESCRIPTION: Demonstrates how to initialize the DriverBehaviour module, start an analysis session, and stop it to retrieve the analysis results. It also includes a check for the validity of the analysis. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/docs/12_driver-behaviour.md#_snippet_0 LANGUAGE: dart CODE: ``` final driverBehaviour = DriverBehaviour( dataSource: myDataSource, useMapMatch: true, ); bool started = driverBehaviour.startAnalysis(); // ... after some driving DriverBehaviourAnalysis? result = driverBehaviour.stopAnalysis(); if (result == null){ print("The analysis is invalid and cannot be used"); return; } ``` -------------------------------- TITLE: Examples: Assets Map Style DESCRIPTION: Shows how to apply a map style from a `.style` asset. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/docs/1_introduction/CHANGELOG.md#_snippet_256 LANGUAGE: flutter CODE: ``` // Example code for applying asset map styles // ... (implementation details would go here) ``` -------------------------------- TITLE: Starting Navigation on a Route DESCRIPTION: Initiates turn-by-turn navigation along the selected main route. It sets up navigation instructions and error handling. The map also starts following the user's position. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/examples/17_routing-navigation/11_navigate-route.md#_snippet_2 LANGUAGE: dart CODE: ``` void _startNavigation() { final routes = _mapController.preferences.routes; if (routes.mainRoute == null) { _showSnackBar(context, message: "No main route available") return; } _navigationHandler = NavigationService.startSimulation( routes.mainRoute!, null, onNavigationInstruction: (instruction, events) { setState(() { _isNavigationActive = true; }); currentInstruction = instruction; }, onError: (error) { setState(() { _isNavigationActive = false; _cancelRoute(); }); if (error != GemError.cancel) { _stopNavigation(); } return; }, ); _mapController.startFollowingPosition(); } ``` -------------------------------- TITLE: Change Alarm Listener DESCRIPTION: This code example shows how to update the AlarmListener associated with an existing AlarmService. It also demonstrates how to register a new callback for a specific event, such as 'onEnterDayMode', emphasizing that only the most recently registered callback will be invoked. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/docs/9_alarms/01_get-started-alarms.md#_snippet_1 LANGUAGE: dart CODE: ``` AlarmListener newAlarmListener = AlarmListener(); alarmService.alarmListener = newAlarmListener; alarmListener.registerOnEnterDayMode(() { showSnackbar("Day mode entered"); }); ``` -------------------------------- TITLE: Recorder Initialization and Usage DESCRIPTION: Demonstrates how to create, start, and stop a recorder using the Maps SDK for Flutter. It highlights the importance of awaiting start and stop methods and setting the correct recorded types. It also mentions the need for location permissions. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/docs/5_positioning/04_recorder.md#_snippet_3 LANGUAGE: dart CODE: ``` String tracksPath = await _getTracksPath(); DataSource? dataSource = DataSource.createLiveDataSource(); if (dataSource == null){ showSnackbar("The datasource could not be created"); return; } RecorderConfiguration recorderConfiguration = RecorderConfiguration( dataSource: dataSource, logsDir: tracksPath, recordedTypes: [DataType.position], ); // Create recorder based on configuration final recorder = Recorder.create(recorderConfiguration); GemError errorStart = await recorder.startRecording(); if (errorStart != GemError.success) { showSnackbar("Error starting recording: $errorStart"); } // Other code GemError errorStop = await recorder.stopRecording(); if (errorStop != GemError.success) { showSnackbar("Error stopping recording: $errorStop"); } ``` -------------------------------- TITLE: Search with Location Hint DESCRIPTION: Demonstrates how to limit a search to a specific geographic area using the `locationHint` parameter. This is achieved by providing a `RectangleGeographicArea` which defines the boundaries for the search. The example shows how to create a `RectangleGeographicArea` and pass it to the search function. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/docs/6_search/01_get-started-search.md#_snippet_7 LANGUAGE: dart CODE: ``` final coords = Coordinates(latitude: 41.68905, longitude: -72.64296); final searchArea = RectangleGeographicArea( topLeft: Coordinates(latitude: 41.98846, longitude: -73.12412), bottomRight: Coordinates(latitude: 41.37716, longitude: -72.02342)); SearchService.search('N', coords, (err, result) { successfulSearchCompleter.complete((err, result)); }, preferences: SearchPreferences(maxMatches: 400), locationHint: searchArea, ); ``` -------------------------------- TITLE: Run Flutter clean and pod install for iOS DESCRIPTION: Executes commands to clean the Flutter project, fetch new dependencies, navigate to the iOS directory, and install CocoaPods dependencies, ensuring the SDK is correctly integrated. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/docs/2_get-started/02_integrate-sdk.md#_snippet_5 LANGUAGE: bash CODE: ``` flutter clean flutter pub get cd ios pod install ``` -------------------------------- TITLE: Map Download UI and Integration DESCRIPTION: This code defines the main application structure, handling map initialization and navigation to the map download page. It includes the MyHomePage widget which sets up the app bar and integrates the GemMap component. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/examples/17_maps-3dscene-examples/15_map-download.md#_snippet_0 LANGUAGE: dart CODE: ``` class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @override State createState() => _MyHomePageState(); } class _MyHomePageState extends State { @override void dispose() { GemKit.release(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.deepPurple[900], title: const Text( 'Map Download', style: TextStyle(color: Colors.white), ), actions: [ IconButton( onPressed: () => _onMapButtonTap(context), icon: const Icon( Icons.map_outlined, color: Colors.white, ), ), ], ), body: GemMap( key: ValueKey("GemMap"), onMapCreated: _onMapCreated, appAuthorization: projectApiToken, ), ); } void _onMapCreated(GemMapController controller) async { SdkSettings.setAllowOffboardServiceOnExtraChargedNetwork( ServiceGroupType.contentService, true); } void _onMapButtonTap(BuildContext context) async { Navigator.of(context).push(MaterialPageRoute( builder: (context) => const MapsPage(), )); } } ``` -------------------------------- TITLE: Search Around Position DESCRIPTION: Explains how to search for landmarks in the closest proximity to a given coordinate. This method can be configured with preferences such as `maxMatches` and `allowFuzzyResults`. The example shows how to initiate a search around a specific location and handle potential errors or empty results. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/docs/6_search/01_get-started-search.md#_snippet_6 LANGUAGE: dart CODE: ``` final coords = Coordinates(latitude: 45, longitude: 10); final preferences = SearchPreferences( maxMatches: 40, allowFuzzyResults: true, ); TaskHandler? taskHandler = SearchService.searchAroundPosition( coords, preferences: preferences, (err, results) async { if (err == GemError.success) { if (results.isEmpty) { showSnackbar("No results"); } else { showSnackbar("Number of results: ${results.length}"); } } else { showSnackbar("Error: $err"); } }, ); ``` -------------------------------- TITLE: RouteRenderSettings API Documentation DESCRIPTION: Comprehensive API documentation for the RouteRenderSettings class, covering constructors, properties, and methods with detailed explanations and usage examples. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/api-references/2.24.0/core/RouteRenderSettings-class-sidebar.html#_snippet_3 LANGUAGE: APIDOC CODE: ``` RouteRenderSettings: Constructors: RouteRenderSettings() Creates a new RouteRenderSettings object with default values. RouteRenderSettings.fromJson(Map json) Creates a RouteRenderSettings object from a JSON map. Properties: directionArrowInnerColor: Color The inner color of the direction arrow. directionArrowOuterColor: Color The outer color of the direction arrow. fillColor: Color The fill color for the route. imagePosition: ImagePosition The position of the image on the route. imgSz: Size The size of the image. innerColor: Color The inner color of the route line. innerSz: Size The inner size of the route line. lineType: LineType The type of line for the route (e.g., solid, dashed). options: RenderOptions Additional rendering options. outerColor: Color The outer color of the route line. outerSz: Size The outer size of the route line. textColor: Color The color of the text displayed on the route. textSz: Size The size of the text displayed on the route. traveledInnerColor: Color The inner color of the traveled portion of the route. turnArrowInnerColor: Color The inner color of the turn arrow. turnArrowInnerSz: Size The inner size of the turn arrow. turnArrowOuterColor: Color The outer color of the turn arrow. turnArrowOuterSz: Size The outer size of the turn arrow. waypointTextInnerColor: Color The inner color of the waypoint text. waypointTextOuterColor: Color The outer color of the waypoint text. waypointTextSz: Size The size of the waypoint text. Methods: toJson(): Map Serializes the RouteRenderSettings object to a JSON map. toJsonWithOptions(RenderOptions options): Map Serializes the RouteRenderSettings object to a JSON map using specified options. operator ==(Object other): bool Compares this RouteRenderSettings object with another object for equality. ``` -------------------------------- TITLE: Get Current Raw Position DESCRIPTION: Retrieves the latest available raw `GemPosition` object. Returns `null` if no position data is currently available. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/docs/5_positioning/01_get-started-positioning.md#_snippet_5 LANGUAGE: dart CODE: ``` GemPosition? position = PositionService.instance.position; if (position == null) { showSnackbar("No position"); } else { showSnackbar("Position: ${position.coordinates}"); } ``` -------------------------------- TITLE: Start Navigation Simulation DESCRIPTION: This Dart function starts the navigation simulation along the main route. It checks if a route is loaded and if the simulation is already active. The camera follows the simulated position. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/examples/17_routing-navigation/06_gpx-route.md#_snippet_3 LANGUAGE: dart CODE: ``` void _startSimulation() { if (_isSimulationActive) return; if (!_isGpxDataLoaded) return; final routes = _mapController.preferences.routes; if (routes.mainRoute == null) { _showSnackBar(context, message: "No route available"); return; } _navigationHandler = NavigationService.startSimulation(routes.mainRoute!, ( eventType, instruction, ) { }, speedMultiplier: 2); _mapController.startFollowingPosition(); setState(() => _isSimulationActive = true); } ``` -------------------------------- TITLE: Start Navigation Simulation DESCRIPTION: Starts a navigation simulation session with the specified parameters and event handlers. This method registers an event listener with the GemKit platform and returns a TaskHandler to manage the session. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/api-references/2.24.0/navigation/NavigationService/startSimulation.html#_snippet_4 LANGUAGE: dart CODE: ``` static TaskHandler startSimulation( { required NavigationConfig config, required Function(NavigationInstruction instruction, List events)? onNavigationInstruction, required Function(Landmark destination)? onDestinationReached, required Function(GemError error)? onError, Function(Route route)? onRouteUpdated, Function(String textToSpeechInstruction)? onTextToSpeechInstruction, Function(NavigationStatus status)? onNotifyStatusChange, Function(Route route)? onBetterRouteDetected, Function()? onBetterRouteRejected, Function()? onBetterRouteInvalidated, Function()? onSkipNextIntermediateDestinationDetected, Function()? onTurnAround, Function(Landmark waypoint)? onWaypointReached, }) { final listener = NavigationEventListener( onNavigationInstruction: (final NavigationInstruction instruction, final List events) { onNavigationInstructionUpdate?.call( NavigationEventType.instructionUpdate, instruction, ); onNavigationInstruction?.call(instruction, events); }, onWaypointReached: onWaypointReached, onDestinationReached: (final Landmark destination) { onNavigationInstructionUpdate?.call( NavigationEventType.destinationReached, null, ); onDestinationReached?.call(destination); }, onNavigationError: (final GemError error) { GemKitPlatform.instance.unregisterEventHandler(listener.id); onNavigationInstructionUpdate?.call(NavigationEventType.error, null); onError?.call(error); }, onRouteUpdated: onRouteUpdated, onNavigationSound: onTextToSpeechInstruction, onNotifyStatusChange: onNotifyStatusChange, onBetterRouteDetected: onBetterRouteDetected, onBetterRouteRejected: onBetterRouteRejected, onBetterRouteInvalidated: onBetterRouteInvalidated, onSkipNextIntermediateDestinationDetected: onSkipNextIntermediateDestinationDetected, onTurnAround: onTurnAround, ); GemKitPlatform.instance.registerEventHandler(listener.id, listener); return TaskHandlerImpl(listener.id); } ``` -------------------------------- TITLE: EntranceLocations Class Overview DESCRIPTION: Provides an overview of the EntranceLocations class, detailing its constructors, properties, and methods. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/api-references/2.24.0/core/EntranceLocations-class-sidebar.html#_snippet_0 LANGUAGE: APIDOC CODE: ``` EntranceLocations: Constructors: - EntranceLocations.init() Properties: - count: Returns the number of entrance locations. - id: Returns the unique identifier for the entrance locations. Methods: - addEntranceLocation(location: dynamic): Adds an entrance location. - dispose(): Disposes of the entrance locations object. - getCoordinates(): Returns the coordinates of the entrance locations. - getType(): Returns the type of the entrance locations. - registerAutoReleaseObject(object: dynamic): Registers an object for automatic release. ``` -------------------------------- TITLE: Get Current Map Matched Position DESCRIPTION: Retrieves the latest available map-matched `GemImprovedPosition` object. Returns `null` if no map-matched position data is currently available. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/docs/5_positioning/01_get-started-positioning.md#_snippet_6 LANGUAGE: dart CODE: ``` GemImprovedPosition? improvedPosition = PositionService.instance.improvedPosition; if (improvedPosition == null) { showSnackbar("No improved position"); } else { showSnackbar("Improved Position: ${improvedPosition.coordinates}"); } ``` -------------------------------- TITLE: Get ETA and Traffic Information DESCRIPTION: Retrieves estimated time of arrival (ETA) and distance for a route. It also shows how to access traffic events along the route, including their affected transport modes, descriptions, severity, and location. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/docs/7_routing/01_get-started-routing.md#_snippet_2 LANGUAGE: dart CODE: ``` TimeDistance td = route.getTimeDistance(activePart: false); final totalDistance = td.totalDistanceM; // same with: //final totalDistance = td.unrestrictedDistanceM + td.restrictedDistanceM; final totalDuration = td.totalTimeS; // same with: //final totalDuration = td.unrestrictedTimeS + td.restrictedTimeS; // by default activePart = true TimeDistance remainTd = route.getTimeDistance(activePart: true); final totalRemainDistance = remainTd.totalDistanceM; final totalRemainDuration = remainTd.totalTimeS; ``` LANGUAGE: dart CODE: ``` List trafficEvents = route.trafficEvents; for (final event in trafficEvents) { RouteTransportMode transportMode = event.affectedTransportModes; String description = event.description; TrafficEventClass eventClass = event.eventClass; TrafficEventSeverity eventSeverity = event.eventSeverity; Coordinates from = event.from; Coordinates to = event.to; bool isRoadBlock = event.isRoadblock; } ``` -------------------------------- TITLE: Create Settings Service DESCRIPTION: Demonstrates how to initialize the SettingsService, either with a default path or a custom one. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/docs/15_settings-service.md#_snippet_0 LANGUAGE: dart CODE: ``` final settings = SettingsService(); final settings = SettingsService(path: "/custom/settings/path"); final String currentPath = settings.path; ``` -------------------------------- TITLE: Flutter App Initialization and UI Setup DESCRIPTION: Initializes the GemKit SDK and sets up the main Flutter application structure, including the MaterialApp and MyHomePage. The MyHomePage manages the state for navigation simulation, route building, and UI updates. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/examples/17_routing-navigation/23_simulate-navigation-without-map.md#_snippet_0 LANGUAGE: dart CODE: ``` Future main() async { WidgetsFlutterBinding.ensureInitialized(); 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: 'Simulate Navigation Without Map', home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @override State createState() => _MyHomePageState(); } class _MyHomePageState extends State { late NavigationInstruction _currentInstruction; // Store the computed route. late Route _route; 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; @override void dispose() { GemKit.release(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text( "Simulate Navigation Without Map", 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: [ if (_isSimulationActive) Positioned( top: 10, left: 10, child: NavigationInstructionPanel( instruction: _currentInstruction, ), ), if (_isSimulationActive) Positioned( bottom: MediaQuery.of(context).padding.bottom + 10, left: 0, child: NavigationBottomPanel( remainingDistance: _currentInstruction.getFormattedRemainingDistance(), eta: _currentInstruction.getFormattedRemainingDuration(), remainingDuration: _currentInstruction.getFormattedETA(), ), ), ], ), resizeToAvoidBottomInset: false, ); } // Custom method for calling calculate route and displaying the results. void _onBuildRouteButtonPressed(BuildContext context) { // Define the departure. final departureLandmark = Landmark.withLatLng( latitude: 51.20830988558932, longitude: 6.6794155000229045, ); // Define the destination. final destinationLandmark = Landmark.withLatLng( latitude: 50.93416933110433, longitude: 6.94370301382495, ); // 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) { _showSnackBar( context, message: 'Successfully calculated the route.', duration: const Duration(seconds: 2), ); setState(() { _route = routes.first; }); } setState(() { _areRoutesBuilt = true; }); }, ); } ``` -------------------------------- TITLE: DriverBehaviourAnalysis startTime Property DESCRIPTION: Gets the start time of the session in milliseconds since epoch. This property relies on the objectMethod to retrieve the start time from the DriverBehaviourAnalysis object. It returns an integer representing the time in milliseconds. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/api-references/2.24.0/driver_behaviour/DriverBehaviourAnalysis/startTime.html#_snippet_0 LANGUAGE: APIDOC CODE: ``` DriverBehaviourAnalysis.startTime Type: int Description: Get the start time of the session in milliseconds since epoch. Returns: The start time of the session in milliseconds since epoch. Throws: * An exception if it fails. Implementation: ```dart int get startTime { final OperationResult resultString = objectMethod( _pointerId, 'DriverBehaviourAnalysis', 'getStartTime', ); return resultString['result']; } ``` ``` -------------------------------- TITLE: Examples: Lane Instructions DESCRIPTION: Shows how to display the lane image corresponding to the current navigation instruction. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/docs/1_introduction/CHANGELOG.md#_snippet_259 LANGUAGE: flutter CODE: ``` // Example code for displaying lane instructions // ... (implementation details would go here) ``` -------------------------------- TITLE: iOS Location Permissions DESCRIPTION: Configures the Info.plist file on iOS to request user permission for location access when the app is in use. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/docs/5_positioning/01_get-started-positioning.md#_snippet_1 LANGUAGE: xml CODE: ``` NSLocationWhenInUseUsageDescription Location is needed for map localization and navigation ``` -------------------------------- TITLE: Android Location Permissions DESCRIPTION: Adds necessary location permissions to the AndroidManifest.xml file for accessing device location, including background location. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/docs/5_positioning/01_get-started-positioning.md#_snippet_0 LANGUAGE: xml CODE: ``` ``` -------------------------------- TITLE: SoundPlayingService Constructors DESCRIPTION: Details on how to create instances of the SoundPlayingService class. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/api-references/2.24.0/core/SoundPlayingService-class-sidebar.html#_snippet_0 LANGUAGE: APIDOC CODE: ``` SoundPlayingService: SoundPlayingService() Constructs a new SoundPlayingService instance. ``` -------------------------------- TITLE: Get Visible Route Interval DESCRIPTION: Explains how to retrieve the portion of a route that is currently visible on the map, returning the start and end distances in meters. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/docs/4_maps/04_display-map-items/04_display-routes.md#_snippet_7 LANGUAGE: dart CODE: ``` final (startRouteVisibleIntervalMeters, endRouteVisibleIntervalMeters) = controller.getVisibleRouteInterval(route); ``` -------------------------------- TITLE: Map Selection Example DESCRIPTION: Demonstrates how to initialize the GemMap, register a callback for landmark taps, and manage the UI state when a landmark is selected. It includes handling map creation, landmark selection, highlighting, and displaying landmark details. SOURCE: https://github.com/magiclane-international/maps-sdk-for-flutter-docs-context7/blob/main/examples/17_maps-3dscene-examples/14_map-selection.md#_snippet_0 LANGUAGE: dart CODE: ``` class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( debugShowCheckedModeBanner: false, title: 'Map Selection', home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @override State createState() => _MyHomePageState(); } class _MyHomePageState extends State { late GemMapController _mapController; Landmark? _focusedLandmark; @override void dispose() { GemKit.release(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.deepPurple[900], title: const Text('Map Selection', style: TextStyle(color: Colors.white)), ), body: Stack(children: [ GemMap( key: ValueKey("GemMap"), onMapCreated: _onMapCreated, appAuthorization: projectApiToken, ), if (_focusedLandmark != null) Align( alignment: Alignment.bottomCenter, child: LandmarkPanel( onCancelTap: _onCancelLandmarkPanelTap, landmark: _focusedLandmark!, )) ]), resizeToAvoidBottomInset: false, ); } // The callback for when map is ready to use. void _onMapCreated(GemMapController controller) { // Save controller for further usage. _mapController = controller; // Listen for map landmark selection events. _registerLandmarkTapCallback(); } void _registerLandmarkTapCallback() { _mapController.registerTouchCallback((pos) async { // Select the object at the tap position. _mapController.setCursorScreenPosition(pos); // Get the selected landmarks. final landmarks = _mapController.cursorSelectionLandmarks(); // Check if there is a selected Landmark. if (landmarks.isNotEmpty) { // Highlight the selected landmark. _mapController.activateHighlight(landmarks); setState(() { _focusedLandmark = landmarks[0]; }); // Use the map controller to center on coordinates. _mapController.centerOnCoordinates(landmarks[0].coordinates); } }); } void _onCancelLandmarkPanelTap() { // Remove landmark highlights from the map. _mapController.deactivateAllHighlights(); setState(() { _focusedLandmark = null; }); } } ```