Try Live
Add Docs
Rankings
Pricing
Docs
Install
Install
Docs
Pricing
More...
More...
Try Live
Rankings
Enterprise
Create API Key
Add Docs
Magiclane Maps SDK for Flutter
https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7
Admin
Magiclane Maps SDK for Flutter is a software development kit that provides mapping functionalities
...
Tokens:
1,205,411
Snippets:
7,613
Trust Score:
3.5
Update:
2 weeks ago
Context
Skills
Chat
Benchmark
85.5
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# Magic Lane Maps SDK for Flutter The Magic Lane Maps SDK for Flutter is a comprehensive mapping and navigation library that enables developers to integrate interactive maps, turn-by-turn navigation, and location-based services into Flutter applications. It provides global coverage using OpenStreetMap data, 3D terrain visualization, offline map support, real-time traffic integration, and optimized routing for car, pedestrian, and bicycle navigation modes. The SDK supports Android (API level 27+) and iOS (14.0+) platforms with web support planned for future releases. Key features include customizable map styles, voice-guided navigation in multiple languages, POI search with category filtering, landmark management, and a sensor recorder for tracking navigation sessions. The SDK requires Dart 3.9.0+ and Flutter 3.35.1+ and is available on pub.dev as the `magiclane_maps_flutter` package. ## GemMap Widget - Display Interactive Map The `GemMap` widget is the core component for rendering interactive maps in your Flutter application. It requires an API token for authorization and provides a callback when the map is ready for interaction. ```dart import 'package:magiclane_maps_flutter/magiclane_maps_flutter.dart'; const projectApiToken = String.fromEnvironment('GEM_TOKEN'); class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { late GemMapController _mapController; @override void dispose() { GemKit.release(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Hello Map')), body: GemMap( key: ValueKey("GemMap"), onMapCreated: (controller) { _mapController = controller; }, appAuthorization: projectApiToken, ), ); } } ``` ## RoutingService.calculateRoute - Calculate Routes Between Locations The `RoutingService.calculateRoute` method computes routes between two or more waypoints, returning a list of route alternatives with distance and duration information. Each waypoint is defined as a `Landmark` with latitude/longitude coordinates. ```dart void calculateRoute() { // Define departure and destination landmarks final departureLandmark = Landmark.withLatLng(latitude: 48.85682, longitude: 2.34375); final destinationLandmark = Landmark.withLatLng(latitude: 50.84644, longitude: 4.34587); // Optional: Add intermediate waypoints final intermediaryPoint = Landmark.withLatLng(latitude: 49.5, longitude: 3.5); // Define route preferences (car, pedestrian, bicycle, truck) final routePreferences = RoutePreferences(); // Calculate route with callback for results TaskHandler? routingHandler = RoutingService.calculateRoute( [departureLandmark, destinationLandmark], routePreferences, (err, routes) { if (err == GemError.success) { // Display routes on map final routesMap = _mapController.preferences.routes; for (final route in routes) { routesMap.add( route, route == routes.first, // Set first route as main label: '${(route.getTimeDistance().totalDistanceM / 1000).toStringAsFixed(1)} km', ); } // Center camera on routes _mapController.centerOnRoutes(routes: routes); } }, ); // Cancel route calculation if needed // RoutingService.cancelRoute(routingHandler); } ``` ## NavigationService.startSimulation - Simulate Turn-by-Turn Navigation The `NavigationService.startSimulation` method starts a simulated navigation session along a calculated route, providing real-time navigation instructions including turn directions, street names, and remaining distance/time. ```dart void startNavigation() { final routes = _mapController.preferences.routes; if (routes.mainRoute == null) { print("No main route available"); return; } // Clear alternative routes, keep only main route routes.clearAllButMainRoute(); NavigationInstruction? currentInstruction; TaskHandler? navigationHandler = NavigationService.startSimulation( routes.mainRoute!, onNavigationInstruction: (instruction, events) { currentInstruction = instruction; // Access navigation data print('Next street: ${instruction.nextStreetName}'); print('Distance to next turn: ${instruction.distanceToNextTurn}m'); print('Remaining distance: ${instruction.remainingTravelDistance}m'); print('Remaining time: ${instruction.remainingTravelTime}s'); // Get turn instruction image if (instruction.nextTurnDetails != null && instruction.nextTurnDetails!.abstractGeometryImg.isValid) { final turnImage = instruction.nextTurnDetails!.abstractGeometryImg .getRenderableImageBytes(size: Size(200, 200), format: ImageFileFormat.png); } }, onError: (error) { if (error == GemError.cancel) { print('Navigation cancelled'); } else { print('Navigation ended or error occurred'); } }, speedMultiplier: 10, // Speed up simulation (optional) ); // Set camera to follow position during navigation _mapController.startFollowingPosition(); // Stop navigation when needed // NavigationService.cancelNavigation(navigationHandler); } ``` ## SearchService.search - Text-Based Location Search The `SearchService.search` method performs text-based searches for landmarks, addresses, and points of interest, returning results sorted by relevance and distance from a reference coordinate. ```dart Future<List<Landmark>> searchLocations(String query, Coordinates referenceCoords) async { Completer<List<Landmark>> completer = Completer<List<Landmark>>(); // Configure search preferences SearchPreferences preferences = SearchPreferences( maxMatches: 40, allowFuzzyResults: true, ); // Perform search SearchService.search(query, referenceCoords, preferences: preferences, (err, results) { if (err != GemError.success) { completer.complete([]); return; } completer.complete(results); }); final landmarks = await completer.future; // Process results for (final landmark in landmarks) { print('Name: ${landmark.name}'); print('Coordinates: ${landmark.coordinates.latitude}, ${landmark.coordinates.longitude}'); // Get address details final address = landmark.address; final street = address.getField(AddressField.streetName); final city = address.getField(AddressField.city); final country = address.getField(AddressField.country); print('Address: $street, $city, $country'); // Get landmark icon if (landmark.img.isValid) { final iconBytes = landmark.img.getRenderableImageBytes(size: Size(50, 50)); } } return landmarks; } ``` ## SearchService.searchAroundPosition - Category-Based POI Search The `SearchService.searchAroundPosition` method searches for points of interest around a location, with optional category filtering for targeted results like restaurants, gas stations, or hotels. ```dart Future<List<Landmark>> searchByCategory(Coordinates center, List<LandmarkCategory> categories) async { Completer<List<Landmark>> completer = Completer<List<Landmark>>(); // Configure search preferences with category filtering SearchPreferences preferences = SearchPreferences( maxMatches: 40, allowFuzzyResults: false, searchMapPOIs: true, searchAddresses: false, ); // Add selected categories to search filter for (final category in categories) { preferences.landmarks.addStoreCategoryId(category.landmarkStoreId, category.id); } // Get available generic categories final availableCategories = GenericCategories.categories; // Search around position with optional text filter SearchService.searchAroundPosition( center, preferences: preferences, textFilter: '', // Optional text filter (err, results) { if (err != GemError.success) { completer.complete([]); return; } completer.complete(results); }, ); return completer.future; } ``` ## PositionService - GPS Location Tracking The `PositionService` manages device location tracking, providing methods to request permissions, set the GPS as the live data source, and enable map following of the device position. ```dart import 'package:permission_handler/permission_handler.dart'; class LocationManager { bool _hasLiveDataSource = false; PermissionStatus _locationPermissionStatus = PermissionStatus.denied; Future<void> startFollowingPosition(GemMapController mapController) async { // Request location permission (Android/iOS) _locationPermissionStatus = await Permission.locationWhenInUse.request(); if (_locationPermissionStatus == PermissionStatus.granted) { // Set GPS as live data source (call only once) if (!_hasLiveDataSource) { PositionService.setLiveDataSource(); _hasLiveDataSource = true; } // Configure smooth animation for camera following final animation = GemAnimation(type: AnimationType.linear); // Start following device position on map mapController.startFollowingPosition(animation: animation); } } // For web platform, use SDK's built-in permission handling Future<void> requestWebPermission() async { final granted = await PositionService.requestLocationPermission(); if (granted == true) { PositionService.setLiveDataSource(); } } } ``` ## ContentStore - Offline Map Download and Management The `ContentStore` class provides methods for downloading, managing, and querying offline map content, enabling full offline functionality for routing and navigation without internet connectivity. ```dart Future<void> downloadOfflineMap(String countryName) async { // Enable content service on charged networks SdkSettings.setAllowOffboardServiceOnExtraChargedNetwork(ServiceGroupType.contentService, true); // Check if map is already downloaded final localMaps = ContentStore.getLocalContentList(ContentType.roadMap); if (localMaps.where((map) => map.name == countryName).isNotEmpty) { print('Map already downloaded'); SdkSettings.setAllowInternetConnection(false); // Enable offline mode return; } // Get list of available maps from server Completer<List<ContentStoreItem>> completer = Completer(); ContentStore.asyncGetStoreContentList(ContentType.roadMap, (err, items, isCached) { if (err == GemError.success) { completer.complete(items); } else { completer.complete([]); } }); final maps = await completer.future; final targetMap = maps.firstWhere((m) => m.name == countryName); // Download map with progress callback targetMap.asyncDownload( (err) { if (err == GemError.success) { print('Download complete'); SdkSettings.setAllowInternetConnection(false); // Enable offline mode } }, onProgress: (progress) { print('Download progress: $progress%'); }, allowChargedNetworks: true, ); // Pause/resume download // targetMap.pauseDownload(); // Delete downloaded map // targetMap.deleteContent(); } ``` ## Markers - Add Custom Markers to Map The markers API allows adding custom markers to the map with configurable icons, labels, and grouping behavior for efficient rendering of large marker sets. ```dart Future<void> addMarkersToMap(GemMapController mapController) async { // Load marker icon from assets final ByteData imageData = await rootBundle.load('assets/marker.png'); final Uint8List markerIcon = imageData.buffer.asUint8List(); // Load group icon for clustered markers final ByteData groupData = await rootBundle.load('assets/group_icon.png'); final Uint8List groupIcon = groupData.buffer.asUint8List(); List<MarkerWithRenderSettings> markers = []; // Create markers with custom render settings for (int i = 0; i < 100; i++) { final marker = MarkerJson( coords: [Coordinates(latitude: 48.8 + (i * 0.01), longitude: 2.3 + (i * 0.01))], name: "Location $i", ); final renderSettings = MarkerRenderSettings( image: GemImage(image: markerIcon, format: ImageFileFormat.png), labelTextSize: 2.0, ); markers.add(MarkerWithRenderSettings(marker, renderSettings)); } // Configure marker collection settings final collectionSettings = MarkerCollectionRenderSettings(); collectionSettings.labelGroupTextSize = 2; collectionSettings.pointsGroupingZoomLevel = 35; // Zoom level for marker grouping collectionSettings.image = GemImage(image: groupIcon, format: ImageFileFormat.png); // Add markers to map mapController.preferences.markers.addList( list: markers, settings: collectionSettings, name: "MyMarkers", ); // Clear all markers // mapController.preferences.markers.clear(); } ``` ## LandmarkStoreService - Manage Favorite Locations The `LandmarkStoreService` provides persistent storage for landmarks, enabling users to save favorite locations, search history, and custom waypoints. ```dart void manageFavorites(Landmark selectedLandmark) { // Get or create a landmark store var favoritesStore = LandmarkStoreService.getLandmarkStoreByName("Favorites"); favoritesStore ??= LandmarkStoreService.createLandmarkStore("Favorites"); // Add landmark to store favoritesStore.addLandmark(selectedLandmark); // Create history store for recent searches var historyStore = LandmarkStoreService.getLandmarkStoreByName("History"); historyStore ??= LandmarkStoreService.createLandmarkStore("History"); historyStore.addLandmark(selectedLandmark); } ``` ## Voice Guidance - Enable Navigation Voice Instructions The SDK supports human voice guidance during navigation with downloadable voice packs in multiple languages. Voice instructions are automatically played during turn-by-turn navigation. ```dart void configureVoiceGuidance() { // Get list of available human voices final voices = ContentStore.getLocalContentList(ContentType.humanVoice); if (voices.isNotEmpty) { // Set voice by file path SdkSettings.setVoiceByPath(voices.first.fileName); } // Enable automatic voice instruction playback SoundPlayingService.canPlaySounds = true; } void startNavigationWithVoice() { final routes = _mapController.preferences.routes; NavigationService.startSimulation( routes.mainRoute!, onNavigationInstruction: (instruction, events) { // Voice instructions play automatically when canPlaySounds is true print('Current instruction: ${instruction.nextStreetName}'); }, onError: (error) { print('Navigation error: $error'); }, speedMultiplier: 20, ); // Enable voice playback SoundPlayingService.canPlaySounds = true; _mapController.startFollowingPosition(); } ``` ## Map Interaction - Highlight and Center on Locations The `GemMapController` provides methods for highlighting landmarks, centering the map on coordinates, and handling touch interactions for route and landmark selection. ```dart void interactWithMap(GemMapController mapController, Landmark landmark) { // Highlight selected landmark on map mapController.activateHighlight( [landmark], renderSettings: HighlightRenderSettings(), ); // Center map on landmark coordinates with zoom level mapController.centerOnCoordinates(landmark.coordinates, zoomLevel: 70); // Register touch callback for route selection mapController.registerOnTouch((pos) async { // Set cursor position for selection await mapController.setCursorScreenPosition(pos); // Get selected routes at touch position final routes = mapController.cursorSelectionRoutes(); if (routes.isNotEmpty) { mapController.preferences.routes.mainRoute = routes[0]; } }); // Transform screen coordinates to map coordinates final screenCenter = Point<int>( MediaQuery.of(context).size.width ~/ 2, MediaQuery.of(context).size.height ~/ 2, ); final mapCoords = mapController.transformScreenToWgs(screenCenter); } ``` ## NavigationInstruction - Access Road Information The `NavigationInstruction` class provides detailed information about the current navigation state, including road signs, lane guidance, and speed limits. Use `getRoadInfoImgByType` for optimized performance when accessing road information images. ```dart void processNavigationInstruction(NavigationInstruction instruction) { // Get road information image using the optimized method (v3.1.8+) RoadInfoImg currentRoadImage = instruction.getRoadInfoImgByType(RoadInfoType.currentRoadInformation); RoadInfoImg nextRoadImage = instruction.getRoadInfoImgByType(RoadInfoType.nextRoadInformation); RoadInfoImg nextNextRoadImage = instruction.getRoadInfoImgByType(RoadInfoType.nextNextRoadInformation); // Access navigation details print('Current street: ${instruction.currentStreetName}'); print('Next street: ${instruction.nextStreetName}'); print('Distance to next turn: ${instruction.distanceToNextTurn}m'); print('Remaining distance: ${instruction.remainingTravelDistance}m'); print('Remaining time: ${instruction.remainingTravelTime}s'); // Get turn visualization if (instruction.nextTurnDetails != null) { final turnImg = instruction.nextTurnDetails!.abstractGeometryImg; if (turnImg.isValid) { final imageBytes = turnImg.getRenderableImageBytes( size: Size(200, 200), format: ImageFileFormat.png, ); } } } ``` The Magic Lane Maps SDK for Flutter is ideal for building navigation apps, fleet management systems, delivery tracking applications, and location-based services that require offline capability. The SDK's comprehensive feature set supports use cases ranging from simple map display to complex multi-waypoint routing with real-time traffic awareness. Integration follows standard Flutter patterns with widgets and async callbacks. Applications should initialize the SDK with a valid API token, handle location permissions appropriately for each platform, and release resources using `GemKit.release()` when the map widget is disposed. For production deployments, download relevant offline maps to ensure functionality in areas with limited connectivity.