# MapLibre Flutter > Permissive and performant mapping library that supports Mapbox Vector Tiles (MVT) powered by MapLibre SDKs. --- Source: https://maplibre.org/flutter-maplibre/docs.md # Overview This is the documentation of [maplibre](https://pub.dev/packages/maplibre), MapLibre Flutter. It renders maps with [MapLibre Native](https://github.com/maplibre/maplibre-native) on Android, iOS, macOS, Windows and Linux, and with [MapLibre GL JS](https://github.com/maplibre/maplibre-gl-js) on web. !!! info "Version 0.4" These docs describe the 0.4 series. If you upgrade from 0.3.x, read the [migration guide](https://maplibre.org/flutter-maplibre/docs/migrate/upgrade-from-v0.3.x.md). ## Getting started - [Installation](https://maplibre.org/flutter-maplibre/docs/getting-started/setup.md): add the package and check the supported platforms. - [Platform setup](https://maplibre.org/flutter-maplibre/docs/getting-started/platforms.md): the setup each platform needs. - [First map](https://maplibre.org/flutter-maplibre/docs/getting-started/usage.md): show a map and control it. - [AI tools](https://maplibre.org/flutter-maplibre/docs/getting-started/ai-tools.md): give AI coding assistants the current docs. ## Guides - [Map & Camera](https://maplibre.org/flutter-maplibre/docs/map.md): map options, camera, gestures, feature queries and paused rendering. - [Styles](https://maplibre.org/flutter-maplibre/docs/styles.md): load a map style. - [Events](https://maplibre.org/flutter-maplibre/docs/events.md): react to taps, camera changes and more. - [User Interface](https://maplibre.org/flutter-maplibre/docs/ui.md): compass, scale bar, attribution and zoom buttons. - [User Location](https://maplibre.org/flutter-maplibre/docs/user-location.md): show and follow the location of the user. - [Offline & Cache](https://maplibre.org/flutter-maplibre/docs/offline.md): download regions for offline use. ## Data on the map - [Annotations](https://maplibre.org/flutter-maplibre/docs/annotations.md): circles, markers, polygons, polylines and widgets, updated with `setState()`. - [Sources](https://maplibre.org/flutter-maplibre/docs/sources.md): GeoJSON, vector and raster tiles, images and video. - [Style Layers](https://maplibre.org/flutter-maplibre/docs/style-layers.md): every layer type of the MapLibre style spec, with typed [expressions](https://maplibre.org/flutter-maplibre/docs/style-layers/expressions.md). ## More - [Migration guides](https://maplibre.org/flutter-maplibre/docs/migrate/upgrade-from-v0.3.x.md) from earlier versions and from maplibre_gl, flutter_map, google_maps_flutter and mapbox_maps_flutter. - [Compare](https://maplibre.org/flutter-maplibre/compare.md) `maplibre` with other map packages. - [Architecture](https://maplibre.org/flutter-maplibre/docs/contributing/architecture.md), [Local development](https://maplibre.org/flutter-maplibre/docs/contributing/development.md) and [API guidelines](https://maplibre.org/flutter-maplibre/docs/contributing/api-guidelines.md) for contributors. --- Source: https://maplibre.org/flutter-maplibre/docs/getting-started/setup.md # Installation ## Add the dependency !!! info "Upgrading from 0.3.x" Version 0.4 changes much of the API. Read the [migration guide](https://maplibre.org/flutter-maplibre/docs/migrate/upgrade-from-v0.3.x.md) when you upgrade. === "Run command" Add `maplibre` to your project by running this command: ```bash flutter pub add maplibre:^0.4.0 ``` === "Edit `pubspec.yaml`" Alternatively, add it directly as a dependency to your `pubspec.yaml` file: ```yaml title="pubspec.yaml" hl_lines="2" dependencies: maplibre: ^0.4.0 ``` and then run `flutter pub get` to install the package. ```bash flutter pub get ``` The packages need Dart 3.13 and Flutter 3.47 or newer. Some platforms need setup steps, see [Platform setup](https://maplibre.org/flutter-maplibre/docs/getting-started/platforms.md). ## Plugins | Package | Used for | |-----------------------|-------------------------------------------------------------------------------------------------------------| | `maplibre_geolocator` | Shows the positions of [geolocator](https://pub.dev/packages/geolocator) as [user location](https://maplibre.org/flutter-maplibre/docs/user-location.md) | ## Platform support | Platform | Implementation | Renderer | Rendering backend | Minimum version | |----------|-------------------|-----------------|----------------------------------------|-------------------------| | Web | `maplibre_web` | MapLibre GL JS | WebGL 2 | Browsers with WebGL 2 | | Android | `maplibre_native` | MapLibre Native | OpenGL ES 3.0 (default) or Vulkan | Android 7.0 (API 24) | | iOS | `maplibre_native` | MapLibre Native | Metal | iOS 15 | | macOS | `maplibre_native` | MapLibre Native | Metal | macOS 14.3 | | Windows | `maplibre_native` | MapLibre Native | Vulkan, shared with Flutter via D3D11 | Vulkan 1.1 driver | | Linux | `maplibre_native` | MapLibre Native | Vulkan, shared with Flutter via OpenGL | Vulkan 1.1 driver | !!! warning "Only on web" Projections other than Mercator and `VideoSource` are only supported on web. On every other platform, `setProjection` keeps Mercator. ## Development version !!! warning The development version is not considered stable and shouldn't be used in production systems. Depend on the packages from the Git repository. `maplibre` depends on the other packages by version, so override them, too: ```yaml title="pubspec.yaml" dependencies: maplibre: git: url: https://github.com/maplibre/flutter-maplibre path: packages/maplibre dependency_overrides: maplibre_native: git: url: https://github.com/maplibre/flutter-maplibre path: packages/maplibre_native maplibre_platform_interface: git: url: https://github.com/maplibre/flutter-maplibre path: packages/maplibre_platform_interface maplibre_web: git: url: https://github.com/maplibre/flutter-maplibre path: packages/maplibre_web ``` --- Source: https://maplibre.org/flutter-maplibre/docs/getting-started/platforms.md # Platform setup This page lists the setup steps of each platform. Required steps are listed first, optional steps are collapsed below them. See [Installation](https://maplibre.org/flutter-maplibre/docs/getting-started/setup.md) for the minimum versions. ## Web ??? note "Optional: choose the version or host maplibre-gl-js yourself" The first map loads the latest [maplibre-gl-js](https://github.com/maplibre/maplibre-gl-js) v6 and [PMTiles](https://github.com/protomaps/PMTiles) v4 from the [jsDelivr](https://www.jsdelivr.com/) CDN. To change that, set `window.flutterMapLibre` in the `` tag of your `web/index.html` file. Every option is optional: ```html title="web/index.html" hl_lines="5-12" ``` | Option | Default | Description | |---------------------|------------|----------------------------------------------------------------------------------------------| | `maplibreGlVersion` | `^6.0.0` | The [npm version range](https://docs.npmjs.com/cli/v10/configuring-npm/package-json#dependencies) of maplibre-gl-js, for example `6.16.0`, `~6.16.0` or `>=6.10.0 <6.15.0`. Only v6 is supported. | | `maplibreGlBaseUrl` | jsDelivr | The URL of a folder with `maplibre-gl.mjs`, `maplibre-gl-worker.mjs` and `maplibre-gl.css` of the same version, for example the `dist` folder of the npm package on your own server. Takes precedence over `maplibreGlVersion`. | | `pmtilesVersion` | `^4.0.0` | The npm version range of PMTiles. | | `pmtilesBaseUrl` | jsDelivr | The URL of a folder with `pmtiles.js`. Takes precedence over `pmtilesVersion`. | ## Android ??? note "Optional: load styles or tiles over `http://`" Android blocks plain `http://` by default. Permit cleartext for the hosts that need it in a [network security config](https://developer.android.com/privacy-and-security/security-config). ??? note "Optional: render with Vulkan" Maps render with OpenGL ES 3.0 by default. To render with Vulkan instead, which needs a device with Vulkan 1.1, select the Vulkan build of the C library in the root `pubspec.yaml` of your app, or of your workspace if your app is part of one: ```yaml title="pubspec.yaml" hooks: user_defines: maplibre_native_ffi: backend: android: vulkan ``` ## iOS **Required:** 1. Raise `IPHONEOS_DEPLOYMENT_TARGET` of the Runner target in `ios/Runner.xcodeproj` to 15.0 if your app targets an older version. 2. Use Swift Package Manager, Flutter's default. If you turned it off, turn it on again: ```bash flutter config --enable-swift-package-manager ``` ??? note "Optional: build for simulators on Apple Silicon only" The C library is published for devices and arm64 simulators. If a simulator build fails to link the x86_64 slice, exclude it in `ios/Flutter/Debug.xcconfig` and `ios/Flutter/Release.xcconfig`: ```text title="ios/Flutter/Debug.xcconfig" EXCLUDED_ARCHS[sdk=iphonesimulator*] = x86_64 ``` ## macOS **Required:** 1. Raise `MACOSX_DEPLOYMENT_TARGET` of the Runner target in `macos/Runner.xcodeproj` to 14.3, as Flutter's template sets an older one. 2. Sandboxed apps need the outgoing network entitlement to load styles and tiles. Add it to `macos/Runner/DebugProfile.entitlements` and `macos/Runner/Release.entitlements`: ```xml com.apple.security.network.client ``` 3. Use Swift Package Manager, Flutter's default. If you turned it off, turn it on again: ```bash flutter config --enable-swift-package-manager ``` ## Linux **Required:** building needs the GTK and libepoxy development packages: ```bash sudo apt install libgtk-3-dev libepoxy-dev ``` --- Source: https://maplibre.org/flutter-maplibre/docs/getting-started/usage.md # First map ## Display your first Map Import the maplibre package and use the `MapLibreMap` widget to display a map. ```dart title="map_screen.dart" linenums="1" hl_lines="3 18-28" import 'package:flutter/material.dart'; import 'package:maplibre/maplibre.dart'; class MapScreen extends StatefulWidget { const MapScreen({super.key}); @override State createState() => MapScreenState(); } class MapScreenState extends State { MapController? _mapController; @override Widget build(BuildContext context) { return Scaffold( body: MapLibreMap( onMapCreated: (controller) { // Store the map controller for later use. You can use it to control // the map programmatically. _mapController = controller; }, onStyleLoaded: (style) { // Add your sources and layers here or do any other setup after the // style has been loaded. debugPrint('Map loaded 😎'); }, ), ); } } ``` The result should look something like this: ![First map](https://maplibre.org/flutter-maplibre/assets/images/first_map.jpg) If the map style isn't specified, the [default MapLibre style](https://github.com/maplibre/demotiles?tab=readme-ov-file#maplibre-world-demo-map) is used. Read the [Styles](https://maplibre.org/flutter-maplibre/docs/styles.md) chapter to learn how to use other styles. ## Programmatic Control It is possible to update or change the `MapLibreMap` widget during its lifetime. ### The `MapLibreMap` widget The `MapLibreMap` is used to specify initial values. Parameters that don't begin with `init*` can be updated in a declarative way just like any other Flutter Widget. The most simple way is to use the `MapLibreMap` widget in a `StatefulWidget` and calling `setState()`. ```dart linenums="1" hl_lines="11 26-28 32-34" @immutable class MyMapWidget extends StatefulWidget { const MyMapWidget({super.key}); @override State createState() => _MyMapWidget(); } class _MyMapWidget extends State { // Using this field to store the widget state bool _gesturesEnabled = true; @override Widget build(BuildContext context) { return Scaffold( body: MapLibreMap( options: MapOptions( // initCamera can't be updated, move the camera with the // MapController instead initCamera: CameraUpdate.position( center: Geographic(lon: 9.17, lat: 47.68), zoom: 3, ), // other parameters can be updated, a new style loads style: MapStyle.url('https://demotiles.maplibre.org/style.json'), gestures: _gesturesEnabled ? MapGestures() : MapGestures.none(), ), onClick: (event) { // update the map widget using Flutters' state management setState(() { _gesturesEnabled = !_gesturesEnabled; }); }, ), ); } } ``` All parameters that start with `init*` can't be updated using this method and need to use the [MapController](#the-mapcontroller) or the [StyleController](#the-stylecontroller). ### The `MapController` The `onMapCreated` callback hands you the `MapController`. You can store the `MapController` in a field variable for later use. ```dart linenums="1" hl_lines="2 15" class _MyMapWidget extends State { MapController? _mapController; @override Widget build(BuildContext context) { return Scaffold( body: MapLibreMap( options: MapOptions( initCamera: CameraUpdate.position( center: Geographic(lon: 9.17, lat: 47.68), zoom: 3, ), ), // store the MapController for later use onMapCreated: (controller) => _mapController = controller, ), ); } } ``` ### The `StyleController` The `StyleController` is a construct to make style related operations on the map. The `onStyleLoaded` callback hands it to you. After it has loaded you can access the `StyleController` at any time from the `style` getter of `MapController`. ```dart linenums="1" hl_lines="13-15" class _MyMapWidget extends State { @override Widget build(BuildContext context) { return Scaffold( body: MapLibreMap( options: MapOptions( initCamera: CameraUpdate.position( center: Geographic(lon: 9.17, lat: 47.68), zoom: 3, ), ), // called every time a style finishes loading onStyleLoaded: (style) { style.sources.add(...); style.layers.add(...); }, ), ); } } ``` Another way to access the `StyleController` is by calling the `style` getter on the `MapController`. Modifications on the map style are only possible after the style has been loaded. In case it hasn't loaded, the getter returns null. ```dart linenums="1" hl_lines="5" MapController? _mapController; void doSomething() { // only adds the source if the style has finished loading and a source can be added. _mapController?.style?.sources.add(...); } ``` ## Next steps - [Map & Camera](https://maplibre.org/flutter-maplibre/docs/map.md) covers the map options, moving the camera and gestures. - [Annotations](https://maplibre.org/flutter-maplibre/docs/annotations.md) add circles, markers, polygons and polylines to the map. - [Sources](https://maplibre.org/flutter-maplibre/docs/sources.md) and [Style Layers](https://maplibre.org/flutter-maplibre/docs/style-layers.md) show your own data with the full MapLibre style spec. --- Source: https://maplibre.org/flutter-maplibre/docs/getting-started/ai-tools.md # Using with AI tools AI assistants often know only older versions of `maplibre` or confuse it with `maplibre_gl`. Point them to the docs below; they follow the [llms.txt](https://llmstxt.org) format and are rebuilt with the website. ## Docs for assistants | File | Content | |------------------------------------------------------------------------|------------------------------------------------------------| | [`llms.txt`](https://maplibre.org/flutter-maplibre/llms.txt) | API summary and an index of all pages. Start here. | | [`llms-full.txt`](https://maplibre.org/flutter-maplibre/llms-full.txt) | All guides in one file. Large. | | `.md` | One page: replace the trailing `/` of its URL with `.md`, e.g. [`docs/map.md`](https://maplibre.org/flutter-maplibre/docs/map.md). | ## Setup Add this to your assistant's rules file (`AGENTS.md`, `CLAUDE.md`, `.cursor/rules` or `.github/copilot-instructions.md`): ```markdown This app uses the Flutter package `maplibre` 0.4. Before writing map code, read https://maplibre.org/flutter-maplibre/llms.txt. Its API differs from older versions and from maplibre_gl. ``` For a docs index such as Cursor's `@Docs`, add `https://maplibre.org/flutter-maplibre/llms-full.txt`. ## Migration skill [`maplibre-migrate`](https://github.com/maplibre/flutter-maplibre/tree/main/skills/maplibre-migrate) is an [Agent Skill](https://agentskills.io) that moves an app to `maplibre` 0.4 from 0.3, `maplibre_gl`, `flutter_map`, `google_maps_flutter` or `mapbox_maps_flutter`. 1. Copy the `maplibre-migrate` folder into your assistant's skills folder, such as `.claude/skills/` for Claude Code. 2. Ask the assistant to migrate the app. Assistants that fetch skills themselves can use [`skills/maplibre-migrate/SKILL.md`](https://maplibre.org/flutter-maplibre/skills/maplibre-migrate/SKILL.md). ## Writing code for 0.4 - Code for 0.3 or older doesn't compile. Signs: `featuresAtPoint`, `MapOptions(initCenter: …)`, `setStyle`, styles as strings, and the `maplibre_android`, `maplibre_ios` and `maplibre_webview` packages. See the [migration guide](https://maplibre.org/flutter-maplibre/docs/migrate/upgrade-from-v0.3.x.md). - Declarative: `MapLibreMap` parameters and annotation layers (`CircleLayer`, `MarkerLayer`, `PolylineLayer`, `PolygonLayer`, `WidgetLayer`); change them with `setState()`. - Imperative: sources and style layers, through `style.sources` and `style.layers`, usually in `onStyleLoaded`. - Variants are sealed classes with named constructors: `MapStyle.url`, `CameraUpdate.position`, `CameraAnimation.fly`, `QueryGeometry.point`, `GeoJsonData.featureCollection`, `MarkerIcon.asset`. - Style layer properties and filters take `Expression`; write constants as `const .literal(…)`. - Positions are `Geographic(lon: …, lat: …)`, bounds are `GeoBox` (geobase, re-exported). - Feature queries and camera methods return futures; `await` them. ## More - [API reference](https://pub.dev/documentation/maplibre/latest/maplibre/): every class and parameter. - [API guidelines](https://maplibre.org/flutter-maplibre/docs/contributing/api-guidelines.md): why the API looks the way it does, for extending it or writing plugins. --- Source: https://maplibre.org/flutter-maplibre/docs/map.md # Map & Camera ## Map options `MapOptions` configures a `MapLibreMap`. Every option except `initCamera`, `fastPforEnabled` and `localIdeographFontFamily` can change at any time, for example with `setState()`, and the map follows: ```dart MapLibreMap( options: MapOptions( style: MapStyle.url('https://demotiles.maplibre.org/style.json'), initCamera: CameraUpdate.position( center: Geographic(lon: 9.17, lat: 47.68), zoom: 7, ), minZoom: 3, maxZoom: 18, maxPitch: 60, maxBounds: GeoBox(west: 5, south: 45, east: 17, north: 55), movements: MapMovements(pitch: false), ), ) ``` | Option | Description | |-------------------------|---------------------------------------------------------------------------------| | `style` | The [map style](https://maplibre.org/flutter-maplibre/docs/styles.md). A new style loads when it changes. | | `initCamera` | Where the map starts, see [below](#initial-camera). Only read once. | | `minZoom`, `maxZoom` | The zoom range the camera stays in. | | `minPitch`, `maxPitch` | The pitch range the camera stays in. | | `maxBounds` | The area the camera stays in. | | `movements` | What the user may change, see [Gestures](#gestures). | | `gestures` | Which gestures move the map, see [Gestures](#gestures). | | `fastPforEnabled` | Decode MLT tiles that use FastPFOR, see [Sources](https://maplibre.org/flutter-maplibre/docs/sources/tiles.md#maplibre-tiles-mlt). Only read once. Always on for web. | | `localIdeographFontFamily` | Draw CJK ideographs, kana and Hangul with the device's fonts, a CSS font-family list, instead of downloading the style's glyphs. Defaults to `'sans-serif'`; `null` draws the style's glyphs. Only read once. Only on iOS, macOS and web. | ## Initial camera `initCamera` sets where the map starts. It takes a `CameraUpdate`, like the camera methods of the controller: - `CameraUpdate.position` starts at a `center`, `zoom`, `bearing`, `pitch` and `roll`. - `CameraUpdate.bounds`, `CameraUpdate.points` and `CameraUpdate.geometry` fit a target into the map from its first frame, inset by `padding`, with an optional `bearing`, `pitch` and `maxZoom`. - Without `initCamera`, the map starts at the camera stored in the style. ```dart MapOptions( initCamera: CameraUpdate.bounds( GeoBox(west: 9.5, south: 47.4, east: 9.8, north: 47.6), padding: EdgeInsets.all(32), ), ) ``` ## Move the camera Use the `MapController` to move the camera after the map was created. Every method takes a `CameraUpdate`, and fields of `CameraUpdate.position` that you leave out keep their value: ```dart // jump to a position await controller.moveCamera( const CameraUpdate.position(center: Geographic(lon: 9.17, lat: 47.68), zoom: 10), ); // ease to a position, 300 ms by default await controller.animateCamera( const CameraUpdate.position(zoom: 12, bearing: 45, pitch: 30), ); // fly to bounds final result = await controller.animateCamera( CameraUpdate.bounds( GeoBox(west: 9.5, south: 47.4, east: 9.8, north: 47.6), padding: const EdgeInsets.all(32), ), animation: const CameraAnimation.fly(duration: Duration(seconds: 2)), ); // the camera that shows some points, without moving the map final camera = await controller.cameraFor(CameraUpdate.points(stops)); ``` `CameraAnimation.ease` interpolates the camera over a `duration` along a `curve`. `CameraAnimation.fly` zooms out and in again like a flight, which suits far targets; without a `duration`, it takes as long as its `speed` needs. `animateCamera` completes when the animation ends, with `CameraAnimationResult.completed`, or with `CameraAnimationResult.cancelled` if a gesture, `moveCamera` or `stopCamera()` stopped it. A later `animateCamera` takes over and completes the earlier one. ## Drive the camera from your app To drive the camera yourself, for example to follow another map or a gesture layer of your own, create the map with `MapLibreMap.withCamera` and rebuild it with a new camera. The map applies each new camera while the widget builds, and its gestures don't move the camera while one is set. ```dart MapLibreMap.withCamera( camera: CameraPosition( center: const Geographic(lon: 9.17, lat: 47.68), zoom: zoom, // from your own state bearing: 0, pitch: 0, ), ) ``` On web the map draws the camera in the same browser frame as the widgets of that build. On every other platform the map image shows it a frame or two later, and `CameraPosition.of(context)` follows the image, so widgets in `MapLibreMap.children` stay on the map. Rebuild with the default constructor to hand the camera back to the gestures and `MapController`. ## Read the camera `MapController.getCamera()` returns the current camera, and the `MapController.camera` getter returns it too, or null before the map is ready. `MapLibreMap.onCameraMove` reports every change. Widgets in `MapLibreMap.children` can read the camera with `CameraPosition.of(context)` and rebuild when it changes. The controller also converts between coordinates and screen positions with `toScreenLocation`, `toLngLat` and their list variants, returns the visible area with `getVisibleBounds()` and the scale with `getMetersPerPixelAtLatitude()`. ## Gestures Gestures are recognized in Flutter and are the same on every platform. Two options decide what they do, and everything is on by default: - `movements` takes a `MapMovements`: what the user may change, with any gesture: `pan`, `zoom`, `rotate` and `pitch`. - `gestures` takes a `MapGestures`: which gestures work. Each one moves the camera only along the movements that are on. | Gesture switch | Gesture | Moves | |-----------------|---------------------------------------------------------------|-------------------| | `drag` | Drag with one finger or the left mouse button | pan | | `fling` | Keep moving after a fast drag or pinch | pan | | `pinch` | Move, spread or twist two fingers on the screen or a trackpad | pan, zoom, rotate | | `scrollWheel` | Scroll wheel | zoom | | `doubleTap` | Double tap or double click | zoom | | `doubleTapDrag` | Double tap and drag up or down | zoom | | `secondaryDrag` | Drag with the right mouse button or Ctrl + left button | rotate, pitch | | `twoFingerDrag` | Drag two fingers side by side up or down | pitch | A pinch rotates the map only once its fingers twist more than `MapGestures.rotateThreshold`, 15 degrees by default, so that zooming and panning with two fingers doesn't turn the map by accident. Set it to 0 to rotate right away. ```dart MapOptions( // No tilting and no rotating. movements: MapMovements(pitch: false, rotate: false), // No scroll wheel zoom; pinching still zooms. gestures: MapGestures(scrollWheel: false), ) // Only pan, by dragging. MapOptions( movements: MapMovements.none(pan: true), gestures: MapGestures.none(drag: true), ) ``` The movements and gestures only stop the user. To keep the camera within limits for the app too, use `minZoom`, `maxZoom`, `minPitch`, `maxPitch` and `maxBounds`. Widgets in `MapLibreMap.children` receive their own taps and drags before the map does. ## Query features `queryRenderedFeatures` returns the features drawn at a screen position (`QueryGeometry.point`), in a rectangle (`.rect`) or anywhere in the map (`.viewport`), optionally only from some layers or matching a filter: ```dart onClick: (event) async { final features = await controller.queryRenderedFeatures( .point(event.screenPoint), layerIds: ['points'], filter: .equal(.get('kind'), .literal('cafe')), ); for (final feature in features) { print('${feature.layerId}: ${feature.properties}'); } }, ``` Each `RenderedFeature` holds its `id`, `properties` and geobase `geometry`, and the `sourceId`, `sourceLayer` and `layerId` it comes from. `querySourceFeatures` returns the features of a source in the tiles it loaded, also those that a filter hides or that lie outside the visible part of the map. A source loads tiles only while a visible layer uses it. For a vector tile source, name the `sourceLayer`: ```dart final countries = await controller.querySourceFeatures( 'openmaptiles', sourceLayer: 'boundary', filter: .equal(.get('admin_level'), const .literal(2)), ); ``` ## Paused rendering A map stops rendering while `MapLibreMap.paused` is true, and keeps its style, camera, sources and cached tiles. Changes made while it is paused show once it resumes. Maps also pause on their own while they are hidden by an `IndexedStack` or a `Visibility` that keeps their state, or while `TickerMode` is disabled, as for a route that another route covers. Set `paused` for the cases Flutter does not report, such as a kept-alive page of a `PageView` or `TabBarView` while another page shows: ```dart MapLibreMap( paused: _tabController.index != 0, options: MapOptions(/* ... */), ) ``` `MapController.isRenderingPaused` and the `onRenderingChanged` callback tell whether the map renders. On web, the browser already skips hidden maps, so `paused` has no effect there. --- Source: https://maplibre.org/flutter-maplibre/docs/styles.md # Styles By default, the default MapLibre style gets used which shows only countries. To change this use the style of a tile provider or create and use your own map style. Custom map styles can be used by setting the `style` parameter of the map options like so: ```dart hl_lines="5" Widget build() { return MapLibreMap( options: MapOptions( style: MapStyle.url('https://demotiles.maplibre.org/style.json'), ) ); } ``` The map loads a new style when `style` changes. The following formats are supported: 1. `MapStyle.url`: the URL of a map style, such as a custom map style served remotely using a URL that starts with `http(s)://`. 2. `MapStyle.asset`: a JSON file in the Flutter assets of the app. 3. `MapStyle.file`: the absolute path of a JSON file, for example in the ApplicationDocumentsDirectory. Not supported on web. 4. `MapStyle.json`: the raw JSON of the map style. Without `MapOptions.initCamera`, the map starts at the camera stored in the style (its `center`, `zoom`, `bearing` and `pitch`). ## Tile sources that require an API key If your tile source requires an API key, it is recommended to directly append it to the url as a query parameter. For example: ```url https://tiles.example.com/{z}/{x}/{y}.pbf?api_key={your_key} ``` ## Use existing styles Every tile provider provides map styles that you can use. !!! warning Note, that the style needs to be compatible with the tile schema used by the tile server. For example OpenMapTiles styles used by MapTiler are not compatible with Protomaps tiles. Have a look at the [awesome-maplibre](https://github.com/maplibre/awesome-maplibre#maptile-providers) list to get an overview over available tile providers that support the MVT standard. ## Create a custom style Map styles are defined in JSON. MapLibre offers a style editor called [Maputnik](https://maplibre.org/maputnik) that allows to customize existing styles or create a new style from scratch. Other tile providers like MapBox have own editors you can use. ![Maputnik Editor](https://maplibre.org/flutter-maplibre/assets/images/maputnik.jpg) ## Label placement transitions Labels fade in and out as their collisions with other labels change, over the style's `transition` duration on native (300 ms unless the style sets one) and over 300 ms on web. `setPlacementTransitions` turns the fade off, so labels show and hide at once: ```dart MapLibreMap( onStyleLoaded: (style) => style.setPlacementTransitions(enabled: false), ) ``` A newly loaded style has them on again. On web, turning it off also ends the crossfade of `*-pattern` and `line-dasharray` values between zoom levels. --- Source: https://maplibre.org/flutter-maplibre/docs/events.md # Events `MapLibreMap` reports user input and state changes through one `on…` callback per event. Set only the callbacks you need: the map doesn't track events that nothing listens to. ## Basic Usage ```dart hl_lines="5-9" @override Widget build(BuildContext context) { return MapLibreMap( options: MapOptions(initCamera: .position(center: Geographic(lon: 9.17, lat: 47.68), zoom: 7)), onMapCreated: (controller) => print('map created'), onStyleLoaded: (style) => print('style loaded'), onClick: (event) => print('clicked at ${event.point.lon}, ${event.point.lat}'), onCameraMoveEnd: (event) => print('camera stopped at ${event.camera.zoom}'), onError: (event) => print('${event.kind}: ${event.message}'), ); } ``` Each callback gets an event object of its own type, such as `MapEventClick` for `onClick`. All of them extend `MapEvent`. ## Available Events Map gestures are recognized in Flutter, so the user input events behave the same on every platform. | Callback | Called when | |-----------------------|---------------------------------------------------------------------------------------------------| | `onMapCreated` | The map was created. Gets the `MapController`. | | `onStyleLoaded` | A style finished loading, also after `MapOptions.style` changed. Gets the `StyleController`. | | `onClick` | The user tapped or clicked the map. | | `onDoubleClick` | The user double tapped or double clicked the map. | | `onSecondaryClick` | The user clicked the map with the secondary (right) mouse button. | | `onLongClick` | The user pressed the map for a longer time. | | `onDragStart` | The user starts to drag the map with one finger or the primary mouse button, see [drags](#drags). | | `onDrag` | The pointer of a drag moved. | | `onDragEnd` | A drag ended. | | `onPointerMove` | A mouse or stylus moved over the map without a pressed button. Touches don't hover. | | `onPointerLeave` | A mouse or stylus left the map. | | `onCameraMoveStart` | The camera starts to move. `reason` says whether a gesture, the app or the map moved it. | | `onCameraMove` | The camera moved. Holds the new `CameraPosition` and the `reason`. | | `onCameraMoveEnd` | The camera stopped moving. Holds the `CameraPosition` it ended at and the `reason`. | | `onIdle` | The map finished rendering and no animation runs. | | `onError` | The style, a source, glyphs or a sprite failed to load, or rendering failed. | | `onStyleImageMissing` | A layer uses an image that the style doesn't have. Add it with `StyleController.addImage`. | | `onLoadingStarted` | The map starts to load a style. | | `onLoadingFinished` | The map loaded its style and what the view needs. | | `onSourceChanged` | A source of the style changed, such as when its TileJSON arrives. | | `onRenderFrame` | The map rendered a frame. Not on web, it holds the frame's statistics. | | `onRenderingChanged` | The map stopped or resumed rendering, see [paused rendering](https://maplibre.org/flutter-maplibre/docs/map.md#paused-rendering). | | `onResize` | The map changed its size. | Some events are not on every platform: | Callback | Platform | Called when | |---------------------------------------|----------|--------------------------------------------------------------------| | `onTile` | not web | A tile moved to another step of loading. | | `onRenderMap` | not web | The map finished rendering a view, partially or fully. | | `onGlyphs` | not web | The map requested or loaded glyphs of a font. | | `onSprite` | not web | The map requested or loaded a sprite. | | `onContextLost`, `onContextRestored` | web | The browser took the map's WebGL context away or gave it back. | | `onProjectionChanged` | web | The map switched its projection. | The click and drag events extend `MapEventUserInput`, which holds the `point` on the map and the `screenPoint` in logical pixels. ## Double taps A double tap zooms in while the zoom gesture of `MapOptions.gestures` is on. To handle it yourself, call `preventDefault()` on the event. `onDoubleClick` can be async, for example to check for features under the tap first. The map waits for it before it zooms: ```dart onDoubleClick: (event) async { final features = await _controller.queryRenderedFeatures( .point(event.screenPoint), ); if (features.isNotEmpty) { event.preventDefault(); // handle the double tap on the feature } }, ``` `preventDefault()` also keeps the double tap and drag gesture from zooming. A tap only waits for a possible second tap while double taps mean something: while `onDoubleClick` is set or the zoom gesture is on. Turn both off and `onClick` fires right away. ## Drags A drag with one finger or the primary mouse button reports `onDragStart` where it went down, `onDrag` while it moves and `onDragEnd` where it stopped. They are reported whether the drag pans the map or not, also while panning is off. A second finger ends the drag and starts a pinch. To move something else instead of the map, call `preventDefault()` on the start event. `onDragStart` can be async to check for features first, and the map holds the pan until it is done: ```dart onDragStart: (event) async { final features = await _controller.queryRenderedFeatures( .point(event.screenPoint), layerIds: ['points'], ); if (features.isNotEmpty) event.preventDefault(); }, onDrag: (event) { // move the feature to event.point }, ``` Annotation layers can do this for their own features, see [Drag annotations](https://maplibre.org/flutter-maplibre/docs/annotations/drag.md). ## Layer events Annotation layers and style layers report taps and the mouse on their own features with `onClick`, `onEnter` and `onLeave`, see click and hover for [annotations](https://maplibre.org/flutter-maplibre/docs/annotations/click-and-hover.md) and for [style layers](https://maplibre.org/flutter-maplibre/docs/style-layers/click-and-hover.md). --- Source: https://maplibre.org/flutter-maplibre/docs/ui.md # User Interface To accomplish a unified and easy to use user interface across the different platforms, the package has some flutter widgets, that are rendered above the map. These UI elements are just like every other Flutter widgets and can be used in the `children` List of the `MapLibreMap` widget. ```dart hl_lines="6-9" @override Widget build(BuildContext context) { return MapLibreMap( // ... children: [ MapScalebar(), SourceAttribution(), MapControlButtons(), MapCompass(), ], ); } ``` See the [styled map page of the example app](https://github.com/maplibre/flutter-maplibre/blob/main/examples/lib/styled_map_page.dart) for a full implementation. All widgets inside the `children` List are within the `MapLibreMap` context and have access to the following helpful functions. - `MapController.maybeOf()` - `MapController.of()` - `CameraPosition.maybeOf()` - `CameraPosition.of()` See [Plugins](https://maplibre.org/flutter-maplibre/docs/plugins.md) for what else a widget in `children` can do. ## Placing Widgets Each widget of this page places itself with its `alignment` and `padding`. To put several of them at the same place without overlapping, wrap them in a `MapAlign`. It stacks them from top to bottom, or side by side with `direction: Axis.horizontal`, and the widgets inside leave out their own `alignment` and `padding`. ```dart MapLibreMap( children: const [ MapAlign( alignment: Alignment.topRight, children: [MapCompass(), MapControlButtons()], ), MapAlign( alignment: Alignment.bottomLeft, children: [MapScalebar()], ), SourceAttribution(), ], ) ``` `MapAlign` is the group, and the widgets of this page are its items: alone, an item places itself, inside a `MapAlign` the group places it. Make your own widgets items with `MapAlignItem`: ```dart MapAlignItem( alignment: Alignment.bottomRight, child: MyButton(), ) ``` Inside a `MapAlign`, `MapAlignItem` shows `MyButton` where the group puts it. Alone, it puts it at the bottom right. ## Source Attribution Many sources require proper attribution to comply with their licensing or terms of service. Use the `SourceAttribution` widget that fetches the attached attributions and displays them on the map. ![Attribution](https://maplibre.org/flutter-maplibre/assets/images/ui/attribution.jpg) ## Map Compass The `MapCompass` widget helps the user orientating by indicating north and gives the user the open to reset the map rotation with a click on the compass. ![Compass](https://maplibre.org/flutter-maplibre/assets/images/ui/compass.jpg) ## Map Scalebar The `MapScalebar` widget shows the current scale of the map center for the current latitude and zoom level. ![Scalebar](https://maplibre.org/flutter-maplibre/assets/images/ui/scalebar.jpg) ## Map Control Buttons Zoom buttons are great for accessibility reasons and great for non-tech-savvy users to navigate the map. You can use the `MapControlButtons` widget to render the default zoom buttons on the map. Set `onTrackingPressed` to show an additional location button, and `tracking` to the tracking of your [UserLocationLayer](https://maplibre.org/flutter-maplibre/docs/user-location.md), which the button shows. See [User Location](https://maplibre.org/flutter-maplibre/docs/user-location.md#tracking) for an example. ![Zoom Control Buttons](https://maplibre.org/flutter-maplibre/assets/images/ui/zoom-buttons.jpg) --- Source: https://maplibre.org/flutter-maplibre/docs/plugins.md # Plugins A plugin is a widget in the `children` of `MapLibreMap`. Plugins can come from your app or from a package, and every widget in `children` can do what a plugin does. ```dart MapLibreMap( layers: [/* the app's own layers */], children: [ const SourceAttribution(), if (measuring) const MeasureLine(), ], ) ``` Adding a plugin to `children` turns it on and removing it turns it off, along with everything it added to the map. ## What a plugin can do ### Read the map Every widget below the map can call these: | Call | Returns | The widget rebuilds when | | ---------------------------------------- | ------------------------------------------------ | ------------------------------------------------------ | | `MapController.of(context)` / `maybeOf` | The controller: camera moves, queries, the style | The controller, options or style change, or the map pauses or resumes rendering | | `CameraPosition.of(context)` / `maybeOf` | The current camera | The camera moves | | `MapOptions.of(context)` / `maybeOf` | The `MapLibreMap.options` | The options change | | `StyleController.of(context)` / `maybeOf` | The loaded style: layers, sources, attributions | A style loads, layers or sources come, go or move, or the attributions change | Only `CameraPosition.of` rebuilds the widget while the camera moves. Use it when a widget shows something that depends on the camera, such as a position on the screen. Use `MapController.of` alone for a widget that only calls the controller, such as a button. `StyleController.of` suits a widget that lists what the style has, such as a layer switcher or a legend. It doesn't rebuild when the properties of a layer or the data of a source change, as apps change those every frame. Code outside of `build` can listen to the `StyleController`, its `layers` or its `sources` instead. ### Draw over the map A plugin builds Flutter widgets that show above the map, like any other widget in `children`. `MapController.toScreenLocations` turns coordinates into positions on the screen. ### Add layers, listen to events and limit movements The `MapPlugin` widget takes the same layers and callbacks as `MapLibreMap`: ```dart class MeasureLine extends StatefulWidget { const MeasureLine({super.key}); @override State createState() => _MeasureLineState(); } class _MeasureLineState extends State { final _points = []; @override Widget build(BuildContext context) => MapPlugin( // Adds a point at every tap. onClick: (event) => setState(() => _points.add(event.point)), // Shown above the layers of MapLibreMap. layers: [ if (_points.length > 1) PolylineLayer(polylines: [Feature(geometry: LineString.from(_points))]), CircleLayer( points: [for (final point in _points) Feature(geometry: Point(point))], ), ], // The user can't rotate the map while the plugin is shown. movements: const MapMovements(rotate: false), // A Flutter widget over the map, laid out like a widget in children. child: const Align(alignment: Alignment.topCenter, child: Text('Tap to measure')), ); } ``` The map combines every `MapPlugin` with its own parameters: - **Layers** show above `MapLibreMap.layers`, the layers of later plugins above those of earlier ones. They stay on the map when the style changes, and their `onClick`, `onEnter`, `onLeave` and `draggable` work as on [annotation layers](https://maplibre.org/flutter-maplibre/docs/annotations.md). - **Taps, clicks, drags and mouse moves** go to the plugins under the pointer first, the topmost first, and then to the callbacks of `MapLibreMap`. Every callback gets the event, so a plugin can't keep it from your app. A plugin can call `preventDefault` on a double click or the start of a drag to stop the map from zooming or panning, and the callbacks after it see that in `defaultPrevented`. - **Other events**, such as camera moves, style loads and errors, go to every plugin and then to `MapLibreMap`. - **Movements and gestures** of a plugin can only turn things off: the user's gestures move the map only the ways that `MapOptions` and every plugin allow. Camera calls, such as `animateCamera`, are not limited. A `MapPlugin` fills the map and never takes a pointer itself, so the map still gets the pointers its `child` lets through. Wrap it in a `Positioned` to receive the taps of only a part of the map. ### Share a corner with other widgets Wrap a plugin's button in a `MapAlignItem`. Alone, it places the button at its own alignment. Inside a `MapAlign`, the group places it next to the built-in widgets without overlapping. See [User Interface](https://maplibre.org/flutter-maplibre/docs/ui.md#placing-widgets). ## Split your map into plugins Plugins aren't only for packages. As a map screen grows, its `MapLibreMap` collects the layers, callbacks and state of every feature on it. Move each feature into a plugin of its own instead, and the screen only lists them: ```dart MapLibreMap( options: MapOptions(style: .url(styleUrl)), children: [ const MapControlButtons(), StopsPlugin(stops: stops, onSelect: (stop) => setState(() => selected = stop)), if (selected != null) SelectedStopPlugin(stop: selected!), if (measuring) const MeasureLine(), ], ) ``` Each plugin keeps what belongs to its feature together: - **Its state, layers and callbacks** live in one widget, not spread over the screen. A tap handler of one feature can't break another. - **Turning a feature on and off** is an `if` in `children`. Removing the plugin removes its layers and callbacks and lifts its movement limits. - **Features stay independent.** Each plugin reads the map through `MapController.of` and `CameraPosition.of`, so it works on every map it is put on, and can move to a package of its own later. Keep a layer or callback on `MapLibreMap` when it belongs to the screen as a whole, such as the base data the screen is about. ## Packages that extend maplibre | Package | What it does | | --------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | [maplibre_geolocator](https://pub.dev/packages/maplibre_geolocator) | Turns the positions of [geolocator](https://pub.dev/packages/geolocator) into the location stream of the [UserLocationLayer](https://maplibre.org/flutter-maplibre/docs/user-location.md) plugin. | | [flutter_map_maplibre](https://pub.dev/packages/flutter_map_maplibre) | Shows [flutter_map](https://pub.dev/packages/flutter_map) layers on a maplibre map, or a maplibre map as a vector layer in flutter_map. | Built a plugin or another package for maplibre? Open a pull request to add it here. --- Source: https://maplibre.org/flutter-maplibre/docs/user-location.md # User Location The `UserLocationLayer` shows the location of the user as a dot with an accuracy circle and a heading, and can move the camera with it. It works the same on every platform. The layer takes a `Stream` and doesn't read the location or ask for permissions itself, so you can use any location source. The [maplibre_geolocator](https://pub.dev/packages/maplibre_geolocator) package turns the positions of [geolocator](https://pub.dev/packages/geolocator) into such a stream. ## Setup Add both packages: ```bash flutter pub add maplibre_geolocator geolocator ``` Set up each platform as the [geolocator documentation](https://pub.dev/packages/geolocator) describes, for example the location permissions in `AndroidManifest.xml` and the usage descriptions in `Info.plist`. ## Show the user location Ask for the location permission, then put a `UserLocationLayer` in the `children` of the map: ```dart linenums="1" hl_lines="11-15 26-27" class _MapScreenState extends State { Stream? _locations; @override void initState() { super.initState(); _requestPermission(); } Future _requestPermission() async { final permission = await Geolocator.requestPermission(); if (permission == LocationPermission.denied || permission == LocationPermission.deniedForever) return; if (!mounted) return; setState(() => _locations = geolocatorUserLocations()); } @override Widget build(BuildContext context) { final locations = _locations; return MapLibreMap( options: MapOptions( initCamera: CameraUpdate.position(zoom: 1), ), children: [ if (locations != null) UserLocationLayer(locations: locations), ], ); } } ``` On Windows, geolocator reports positions only after the app asked for the permission, and `permission_handler` doesn't ask there, so use `Geolocator.requestPermission()`. To use another location source, create `UserLocation`s with a `position` and an optional `accuracy` in meters, `heading` in degrees and `timestamp`. ## Tracking `tracking` moves the camera with the location: - `UserLocationTracking.none`: the camera stays where it is. - `UserLocationTracking.position`: the camera centers on the location. - `UserLocationTracking.positionAndHeading`: the camera also turns with the heading. When the user drags or zooms the map, the layer stops tracking and calls `onTrackingChanged` with `UserLocationTracking.none`. `MapControlButtons` shows a location button for it when you set `onTrackingPressed`: ```dart UserLocationTracking _tracking = UserLocationTracking.position; @override Widget build(BuildContext context) { return MapLibreMap( children: [ UserLocationLayer( locations: locations, tracking: _tracking, trackingZoom: 15, onTrackingChanged: (tracking) => setState(() => _tracking = tracking), ), MapControlButtons( tracking: _tracking, onTrackingPressed: () => setState(() => _tracking = UserLocationTracking.position), ), ], ); } ``` `trackingZoom` is the zoom the camera moves to when tracking starts, and `trackingDuration` how long it takes to follow a new location. ## Style `style` changes how the location looks, with a `UserLocationStyle`: ```dart UserLocationLayer( locations: locations, style: const UserLocationStyle( color: Color(0xFF2E7D32), radius: 10, showAccuracy: false, ), // Below the labels of the style. anchor: const LayerAnchor.below('place_label'), onClick: (location) => print('Tapped my location'), ) ``` - `color` and `radius` set the dot, and the accuracy circle and the heading take the color too. - `showAccuracy` and `showHeading` hide the accuracy circle and the heading cone. - `icon` replaces the dot, for example with an arrow. While `rotateIcon` is set, it turns with the heading and shows it instead of the cone; otherwise it stays upright on the screen. The location is drawn with style layers of the map, so the map draws it in the same frame as everything else and it never trails the camera. It moves from one location to the next without an animation in between. The accuracy circle and the heading lie flat on a tilted map. `anchor` places the layers among those of the style, and `onClick` reports taps on the location. Check out the [example app](https://github.com/maplibre/flutter-maplibre/blob/main/examples/lib/user_location_page.dart) for a full implementation. --- Source: https://maplibre.org/flutter-maplibre/docs/offline.md # Offline & Cache !!! note The `OfflineManager` runs on Android, iOS, macOS, Windows and Linux. On web, `OfflineManager.createInstance()` throws an `UnsupportedError`; a service worker cache is the alternative there. Maps and the `OfflineManager` share one database, `maplibre_native.db` in the app support directory. Maps cache the resources they load in it, and show the regions you downloaded without network access. The `OfflineManager` provides a set of tools to manage the cache and handle offline maps. It enables users to download and interact with map data in areas with limited or no internet access. Here, we’ll cover key features, usage concepts, and API details for `OfflineManager`. The download manager needs to be created asynchronous by using `OfflineManager.createInstance()`. You can store the instance for later use. ```dart Future futureManager = OfflineManager.createInstance(); ``` Don't forget to call `manager.dispose()` when you no longer need it. You can do this for example in the `dispose` override of a flutter widget: ```dart hl_lines="3" @override void dispose() { manager.dispose(); super.dispose(); } ``` ## Cache Management There are mutliple methods to manage and control the cache, ensuring efficient use of storage. Head over to the [API docs](https://pub.dev/documentation/maplibre/latest/maplibre/OfflineManager-class.html) to learn more. ## Downloading Map Regions Using OfflineManager, you can bulk-download specific map regions for offline access. An `OfflineRegionDefinition` says what a region covers: - `OfflineTilePyramidRegionDefinition` downloads every tile within a `GeoBox`. - `OfflineGeometryRegionDefinition` downloads only the tiles that a geometry touches, such as a route as a `LineString` or an area as a `Polygon`. It needs far fewer tiles than the bounding box of a long or diagonal route. Both download the tiles from `minZoom` to `maxZoom`, or to the maximum zoom level of each tile source if that is lower. ```dart Future downloadMyMap() async { final stream = manager.downloadRegion( definition: OfflineTilePyramidRegionDefinition( bounds: GeoBox(/* ... */), styleUrl: '...', minZoom: 10, maxZoom: 14, pixelRatio: 1, ), metadata: {'name': 'Bregenz'}, ); await for (final update in stream) { if (update.downloadCompleted) { print('region downloaded: ${update.region}'); } else { final status = update.status; print( '${status.completedResourceCount} / ${status.requiredResourceCount} ' '(${((update.progress ?? 0) * 100).toStringAsFixed(0)}%)', ); } } } final route = OfflineGeometryRegionDefinition( geometry: LineString.from(const [ Geographic(lon: 9.7471, lat: 47.5031), Geographic(lon: 9.6838, lat: 47.5459), ]), styleUrl: '...', minZoom: 10, maxZoom: 15, pixelRatio: 1, ); ``` Resources that fail to load arrive as `OfflineResourceException` errors on the stream, with the `reason` they failed, and the download retries them. A region with more tiles than the offline database allows stops with an `OfflineTileCountLimitException`. Cancelling the subscription pauses the download; `manager.resumeDownload(regionId: id)` continues it. `manager.getRegionStatus(regionId: id)` reports how far the download of a region got, also while no download runs: the downloaded and required resources and tiles, their size, and whether it is complete. ## Managing Offline Regions After regions are downloaded, they can be managed using methods to list, merge, or retrieve specific region details: ### Listing Offline Regions Get a list of all downloaded regions for management or display purposes by using `manager.listOfflineRegions()`. ### Retrieving a Specific Region Fetch a region’s details with `manager.getOfflineRegion(regionId: 1)`, which is useful for managing or displaying region-specific data. It returns null when there is no region with that id. ### Merging Regions Use `manager.mergeOfflineRegions(path: 'path/to/database')` to merge offline regions from a secondary offline database into the main offline database. This is typically used when you have multiple MapLibre offline databases that you want to consolidate. ### Updating and Deleting Regions `manager.updateRegionMetadata(regionId: 1, metadata: {...})` replaces the metadata of a region, `manager.invalidateRegion(regionId: 1)` loads its resources again once they are needed, and `manager.deleteRegion(regionId: 1)` removes it. --- Source: https://maplibre.org/flutter-maplibre/docs/network.md # Network `MapLibreNetwork` holds static settings for how maps request their styles, tiles, glyphs, sprites and images. They apply to every map, the ones that exist and the ones created later, and to the downloads of the [`OfflineManager`](https://maplibre.org/flutter-maplibre/docs/offline.md). A change reaches the requests that follow it; resources that are already loaded or cached stay as they are. ## Request headers `requestHeaders` sends extra HTTP headers, for example an API key for your own tile server: ```dart MapLibreNetwork.requestHeaders = [ RequestHeaders( {'Authorization': 'Bearer $token'}, url: 'https://tiles.example.com/**', ), RequestHeaders( {'X-Client': 'my-app'}, kinds: {MapResourceKind.style}, ), ]; ``` The first entry that matches a request adds its headers, and no other. An entry matches when the whole URL, query included, matches its glob `url` and the request is of one of its `kinds` (every kind by default): | Pattern | Matches | |---------|--------------------------------------------| | `*` | Any characters except `/` | | `**` | Any characters | | `?` | One character except `/` | | `\` | Makes the next character match only itself | Headers that the platform manages, such as `Host`, `User-Agent` or `Range`, can't be set. On web, a cross-origin request with custom headers needs the server to allow them (a CORS preflight). ## URL transform `urlTransform` rewrites the URL of each request before it is sent, for example to add a key as a query parameter or to point a style at another server: ```dart MapLibreNetwork.urlTransform = (url, kind) { if (kind == MapResourceKind.tile && url.startsWith('https://tiles.example.com/')) { return '$url?key=$apiKey'; } return url; }; ``` Return the URL unchanged to keep it. The transform runs for every request, so keep it fast. If it throws, the error goes to `FlutterError.onError` and the request keeps its URL. Request headers match the transformed URL. `MapLibreNetwork.reset()` removes the headers and the transform. --- Source: https://maplibre.org/flutter-maplibre/docs/annotations.md # Annotation Layers Annotation layers show your own points, lines and areas on the map. Put them in the `MapLibreMap.layers` list and change them like any other widget parameter, with `setState()` or the state management of your choice. The map adds, updates and removes only what changed. | Layer | Geometry | Built on | |-------------------------------|----------------|----------------------------------------------------------------| | [`CircleLayer`](#circles) | `Point` | [`CircleStyleLayer`](https://maplibre.org/flutter-maplibre/docs/style-layers.md#circle) | | [`MarkerLayer`](#markers) | `Point` | [`SymbolStyleLayer`](https://maplibre.org/flutter-maplibre/docs/style-layers.md#symbol) | | [`PolygonLayer`](#polygons) | `Polygon` | [`FillStyleLayer`](https://maplibre.org/flutter-maplibre/docs/style-layers.md#fill) | | [`PolylineLayer`](#polylines) | `LineString` | [`LineStyleLayer`](https://maplibre.org/flutter-maplibre/docs/style-layers.md#line) | Flutter widgets on the map go into a [`WidgetLayer`](https://maplibre.org/flutter-maplibre/docs/annotations/widgets.md). For large or frequently changing data, add a [source](https://maplibre.org/flutter-maplibre/docs/sources.md) and a [style layer](https://maplibre.org/flutter-maplibre/docs/style-layers.md) to the style instead. ## Circles Circles ```dart linenums="1" hl_lines="5-16" @override Widget build(BuildContext context) { return MapLibreMap( options: MapOptions(initCamera: .position(center: Geographic(lon: 9.17, lat: 47.68), zoom: 7)), layers: [ CircleLayer( points: const [ Feature(geometry: Point(Geographic(lon: 9.17, lat: 47.68))), Feature(geometry: Point(Geographic(lon: 9.17, lat: 48))), Feature(geometry: Point(Geographic(lon: 9, lat: 48))), Feature(geometry: Point(Geographic(lon: 9.5, lat: 48))), ], color: .literal(Colors.orange.withValues(alpha: 0.5)), radius: const .literal(20), strokeColor: const .literal(Colors.red), strokeWidth: const .literal(2), ), ], ); } ``` See the [example app](https://github.com/maplibre/flutter-maplibre/blob/main/examples/lib/layers_circle_page.dart). ## Markers Markers Markers show an icon, a label or both. The `icon` of the layer is its image, which the map adds to the style for it: ```dart linenums="1" hl_lines="13-20" final _points = >[ const Feature(geometry: Point(Geographic(lon: 9.17, lat: 47.68))), const Feature(geometry: Point(Geographic(lon: 9, lat: 48))), ]; @override Widget build(BuildContext context) { return MapLibreMap( options: MapOptions(initCamera: .position(center: Geographic(lon: 9.17, lat: 47.68), zoom: 7)), // add a marker where the user taps onClick: (event) => setState(() => _points.add(Feature(geometry: Point(event.point)))), layers: [ MarkerLayer( points: _points, icon: const .iconData(Icons.location_on, color: Colors.red), textField: const .literal('Marker'), textAllowOverlap: const .literal(true), iconAnchor: const .literal(IconAnchor.bottom), textOffset: const .literal(Offset(0, 1)), ), ], ); } ``` A `MarkerIcon` is one of: | Icon | Image | |------------------------------------------|---------------------------------------------------------| | `.iconData(Icons.place, color:, size:)` | An icon font glyph, `size` logical pixels large (48) | | `.asset('assets/pin.png', pixelRatio:)` | A Flutter asset | | `.bytes(pngBytes, pixelRatio:)` | Encoded image bytes, such as a PNG | | `.provider(NetworkImage(url))` | Any `ImageProvider`, at the scale of the image it loads | | `.named('pin')` | An image the style already has, from its sprite or `addImage` | | `.expression(Expression.get('icon').asString())` | Per feature, an image the style already has | For `.iconData()`, `.asset()`, `.bytes()` and `.provider()`, the map adds each image once, shares it between the layers with an equal icon, removes it once no layer shows it, and adds it again when another style loads. Images that `.named()` and `.expression()` refer to come from the style, so add an image of your own again with `addImage` after another style loads. See the [example app](https://github.com/maplibre/flutter-maplibre/blob/main/examples/lib/layers_marker_page.dart). ## Polygons Polygons ```dart linenums="1" hl_lines="5-23" @override Widget build(BuildContext context) { return MapLibreMap( options: MapOptions(initCamera: .position(center: Geographic(lon: 9.17, lat: 47.68), zoom: 7)), layers: [ PolygonLayer( polygons: [ Feature( geometry: Polygon.from(const [ [ Geographic(lon: 8.2013, lat: 48.1074), Geographic(lon: 8.8853, lat: 48.0943), Geographic(lon: 8.7597, lat: 47.6933), Geographic(lon: 9.6320, lat: 48.0893), Geographic(lon: 8.6854, lat: 48.4538), Geographic(lon: 8.2013, lat: 48.1074), ], ]), ), ], color: .literal(Colors.lightBlueAccent.withValues(alpha: 0.6)), outlineColor: const .literal(Colors.blue), ), ], ); } ``` See the [example app](https://github.com/maplibre/flutter-maplibre/blob/main/examples/lib/layers_polygon_page.dart). ## Polylines Polylines ```dart linenums="1" hl_lines="5-19" @override Widget build(BuildContext context) { return MapLibreMap( options: MapOptions(initCamera: .position(center: Geographic(lon: 9.17, lat: 47.68), zoom: 7)), layers: [ PolylineLayer( polylines: [ Feature( geometry: LineString.from(const [ Geographic(lon: 9.17, lat: 47.68), Geographic(lon: 9.5, lat: 48), Geographic(lon: 9, lat: 48), ]), ), ], color: const .literal(Colors.red), width: const .literal(4), blur: const .literal(3), dashArray: const .literal([5, 5]), ), ], ); } ``` See the [example app](https://github.com/maplibre/flutter-maplibre/blob/main/examples/lib/layers_polyline_page.dart). ## Ids Every annotation layer is a style layer with a GeoJSON source of the same id. Set `id` to name them: ```dart CircleLayer(id: 'stops', points: stops) ``` The id must not be in use by a layer or source of the style, or by another layer of the list, and must not start with `maplibre-`, which the map uses. It also tells a rebuild which layer is which, like a `Key` of a widget: a layer with an id keeps its style layer and source wherever it moves in the list. Layers without an id match the next layer of the same type without an id, in the order of the list. Read and query the style layers by these ids, for example with `queryRenderedFeatures(layerIds: ['stops'])`. Change them only through `MapLibreMap.layers`: `style.layers.remove()` and `.move()` fail for them, and their setters warn in debug builds, as the next rebuild would undo the change. The same goes for their sources: `style.sources.updateGeoJsonData()` warns for them. ## Order and anchors Layers with the same anchor draw in the order of the list, the first at the bottom, like the children of a `Stack`. A reordered list moves the style layers. By default the annotation layers go on top of the style. `anchor` places a layer elsewhere, and layers with different anchors draw where their anchors put them: ```dart PolylineLayer( polylines: routes, // below the labels of the style anchor: const .below('road-label'), ) ``` | Anchor | Place | |---------------------|-------------------------------------------| | `.top()` | Above every layer of the style (default) | | `.bottom()` | Below every layer of the style | | `.below('layerId')` | Right below the style layer `layerId` | | `.above('layerId')` | Right above the style layer `layerId` | Layers with the same anchor keep the order of the list among themselves. `.below()` and `.above()` name a layer of the style, not one of the list. If the current style has no such layer, the layer goes on top and debug builds print a warning. The layers keep their place when the app adds, moves or removes style layers later, for example once a layer named by an anchor is added. The layers, their sources and their icons stay on the map when another style loads. ## Style each feature Every style parameter is an [expression](https://maplibre.org/flutter-maplibre/docs/style-layers/expressions.md), so it can depend on the properties of each feature: ```dart CircleLayer( points: points, radius: .get('size').asNumber(), color: .get('color').convertToColor(), ) ``` A map can show any number of annotation layers, each with its own style. For properties that the annotation layers don't have, use the [style layer](https://maplibre.org/flutter-maplibre/docs/style-layers.md) they are built on. ## Interaction - [Click and Hover](https://maplibre.org/flutter-maplibre/docs/annotations/click-and-hover.md): react to taps and the mouse on features. - [Drag](https://maplibre.org/flutter-maplibre/docs/annotations/drag.md): let the user move features. --- Source: https://maplibre.org/flutter-maplibre/docs/annotations/widgets.md # Widget Annotations The `WidgetLayer` jumps a bit out of the row when compared to the other annotation layers. ## Differences to other Layers - The `WidgetLayer` is the only built-in map layer that has support for all kind of flutter widgets. - As the `WidgetLayer` is just a Widget itself, it needs to be placed in the `children` list. All the map layers need to be placed in the `layers` list. - `WidgetLayer`s will always be displayed above other layers as it is not part of the map style but displayed above. ## Basic Usage ```dart linenums="1" hl_lines="14-32" @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Widget Layer')), body: MapLibreMap( options: MapOptions( initCamera: CameraUpdate.position( center: Geographic(lon: 0, lat: 0), zoom: 3, ), ), children: [ WidgetLayer( markers: [ Marker( // must be the same dimension as the inner widget size: const Size.square(50), // the longitude / latitude position on the map point: Geographic(lon: -10, lat: 0), // child can be any flutter widget tree child: const Icon( Icons.location_on, color: Colors.red, // must be the same as Marker.size size: 50, ), // the used Icon should be attached to the map at the bottom center alignment: Alignment.bottomCenter, ), ], ), // display the UI widgets above the widget markers. const SourceAttribution(), ], ), ); } ``` By default, widgets in the `WidgetLayer` will stay upright when the map gets rotated or pitched. You are able to change this behavior with the `flat` and `rotate` flags. ## Update To add, remove or alter annotation layers, just use `setState()` like you'd do with Flutter widgets. Check out the [example app](https://github.com/maplibre/flutter-maplibre/blob/main/examples/lib/widget_layer_page.dart) if you want to see how things come together. --- Source: https://maplibre.org/flutter-maplibre/docs/annotations/drag.md # Drag Annotations Every annotation layer can let the user drag its features. Set `draggable: true`, and a drag that starts on a feature of the layer moves that feature instead of the map. Try it in the demo. ## Basic Usage The layer moves the feature itself while it is dragged, so the app doesn't rebuild on every step. When the user drops it, save the new place in `onDragEnd`. Otherwise the feature goes back where it was, because the list of the layer still has it there: ```dart linenums="1" hl_lines="11-14" final _points = >[ const Feature(geometry: Point(Geographic(lon: 9.17, lat: 47.68))), ]; @override Widget build(BuildContext context) { return MapLibreMap( layers: [ CircleLayer( points: _points, draggable: true, onDragEnd: (event) => setState(() { _points[event.index] = Feature(geometry: Point(event.point)); }), ), ], ); } ``` `onDragStart` and `onDrag` report the start and every step of the drag, for example to show where the feature is. Each `LayerFeatureEvent` holds: - `index`: the dragged feature in the layer's list. - `feature`: the dragged feature as it is in the list. - `geometry`: the feature's geometry, moved as far on screen as the pointer. A polygon or a line moves as a whole. - `point` and `screenPoint`: where a point feature moves to, or where the pointer is for other features. ## Details - A drag grabs a feature within a few pixels of where it went down, the nearest one if several are close, of the top-most draggable layer. - A drag that starts beside every draggable feature pans the map as usual. - While it is dragged, the feature is drawn by a layer of its own above its layer, so each step costs the same however many features the layer has. - The map's own `onDragStart`, `onDrag` and `onDragEnd` still fire. The start event of a drag that grabbed a feature has `defaultPrevented` set. - To drag something other than an annotation, such as the features of a style layer, use the map's [drag events](https://maplibre.org/flutter-maplibre/docs/events.md#drags). - Widgets in a `WidgetLayer` take their own gestures, see [Widgets](https://maplibre.org/flutter-maplibre/docs/annotations/widgets.md). --- Source: https://maplibre.org/flutter-maplibre/docs/annotations/click-and-hover.md # Click and Hover Every annotation layer reports taps and the mouse on its features: - `onClick`: the user tapped or clicked a feature. - `onEnter`: a mouse or stylus moved onto a feature, or from one feature of the layer onto another. - `onLeave`: the mouse or stylus left the feature that `onEnter` reported. Try it in the demo. ## Hover effect Keep the hovered feature in the state and draw it again in a second, more opaque layer: ```dart linenums="1" hl_lines="8-11" int? _hovered; @override Widget build(BuildContext context) { return MapLibreMap( layers: [ PolygonLayer( polygons: _areas, opacity: const .literal(0.3), onEnter: (event) => setState(() => _hovered = event.index), onLeave: (event) => setState(() => _hovered = null), ), PolygonLayer( polygons: [if (_hovered case final hovered?) _areas[hovered]], opacity: const .literal(0.6), ), ], ); } ``` ## Details - Each `LayerFeatureEvent` holds the feature's `index` in the layer's list, the `feature` itself, its `geometry`, and where the pointer is as `point` and `screenPoint`. - Of features of several layers, a tap goes to the layer drawn on top, which [anchors](https://maplibre.org/flutter-maplibre/docs/annotations.md#order-and-anchors) can make differ from the last in the list, and of its points to the nearest. A tap next to a small feature still hits it. `MapLibreMap.onClick` is called as well. - `onEnter` and `onLeave` are tracked per layer, also while the list is reordered: moving from a feature of one layer onto an overlapping feature of a layer above enters the second without leaving the first. - Touches don't hover, so `onEnter` and `onLeave` are only called for mice and styluses. Use `onClick` on touch screens. --- Source: https://maplibre.org/flutter-maplibre/docs/sources.md # Sources A source holds data for the map, and [style layers](https://maplibre.org/flutter-maplibre/docs/style-layers.md) draw it. Several layers can use the same source, for example a fill and a line layer for the areas and outlines of the same polygons. | Source | Data | Shown by | |------------------------------------------------------------|-------------------------------------------------------|-----------------------------------| | [`GeoJsonSource`](https://maplibre.org/flutter-maplibre/docs/sources/geojson.md) | Points, lines and polygons, optionally clustered | Circle, fill, heatmap, line, symbol layers | | [`VectorSource`](https://maplibre.org/flutter-maplibre/docs/sources/tiles.md#vector-tiles) | Vector tiles (MVT or MLT), also from PMTiles and MBTiles | Circle, fill, heatmap, line, symbol layers | | [`RasterSource`](https://maplibre.org/flutter-maplibre/docs/sources/tiles.md#raster-tiles) | Image tiles, such as satellite imagery | Raster layer | | [`RasterDemSource`](https://maplibre.org/flutter-maplibre/docs/sources/tiles.md#raster-dem-tiles) | Elevation tiles | Hillshade and color relief layers | | [`ImageSource`](https://maplibre.org/flutter-maplibre/docs/sources/media.md#image) | One image at four coordinates | Raster layer | | [`VideoSource`](https://maplibre.org/flutter-maplibre/docs/sources/media.md#video) | One video at four coordinates, only on web | Raster layer | Every source has a named constructor for its input, such as `GeoJsonSource.url` and `GeoJsonSource.data`. Add sources once the style has loaded: ```dart MapLibreMap( onStyleLoaded: (style) async { await style.sources.add( const VectorSource.url(id: 'roads', url: 'https://example.com/tiles.json'), ); }, ) ``` ## Read and update sources `style.sources` holds the sources of the style. It reads synchronously, and is filled once the style has loaded. Sources are immutable, so an update replaces the object: ```dart final source = style.sources['points']; await style.sources.updateGeoJsonData('points', .text(geoJsonString)); await style.sources.updateGeoJsonUrl('points', 'https://example.com/data.geojson'); await style.sources.updateImageCoordinates('radar', coordinates); await style.sources.updateTiles('roads', ['https://example.com/{z}/{x}/{y}.pbf']); await style.sources.updateTileJsonUrl('roads', 'https://example.com/tiles.json'); await style.sources.remove('points'); ``` See [GeoJSON](https://maplibre.org/flutter-maplibre/docs/sources/geojson.md#update-the-data) and [Tiles](https://maplibre.org/flutter-maplibre/docs/sources/tiles.md) for what the updates do. --- Source: https://maplibre.org/flutter-maplibre/docs/sources/geojson.md # GeoJSON Source You can use the [GeoJsonSource](https://pub.dev/documentation/maplibre/latest/maplibre/GeoJsonSource-class.html) to attach data like points, lines or polygons, from a GeoJSON file with `GeoJsonSource.url` or from `GeoJsonData` with `GeoJsonSource.data`. The data can then be used in a [CircleStyleLayer](https://maplibre.org/flutter-maplibre/docs/style-layers.md#circle), [FillStyleLayer](https://maplibre.org/flutter-maplibre/docs/style-layers.md#fill), [HeatmapStyleLayer](https://maplibre.org/flutter-maplibre/docs/style-layers.md#heatmap), [LineStyleLayer](https://maplibre.org/flutter-maplibre/docs/style-layers.md#line) or [SymbolStyleLayer](https://maplibre.org/flutter-maplibre/docs/style-layers.md#symbol). `GeoJsonData` takes geobase objects, or GeoJSON that you already have as text or as decoded JSON. Text skips building objects in Dart, which matters for large data: on web the browser parses it. ```dart // geobase objects await style.sources.add( GeoJsonSource.data( id: 'points', data: .featureCollection( FeatureCollection([ Feature(geometry: Point(Geographic(lon: 9.17, lat: 47.68))), ]), ), ), ); // GeoJSON text, such as a file or a response body await style.sources.add( GeoJsonSource.data(id: 'routes', data: .text(response.body)), ); ``` ## Clusters A `GeoJsonCluster` groups nearby points into clusters. Cluster features have the properties `cluster`, `cluster_id` and `point_count`, plus the cluster properties you define: ```dart await style.sources.add( GeoJsonSource.url( id: 'earthquakes', url: 'https://example.com/earthquakes.geojson', cluster: GeoJsonCluster( radius: 50, properties: { 'sum': ClusterProperty( reduce: .sum([ Expression.accumulated().asNumber(), Expression.get('sum').asNumber(), ]), map: .get('mag'), ), }, ), ), ); final clusterId = feature.properties['cluster_id']! as int; final zoom = await controller.getClusterExpansionZoom('earthquakes', clusterId); final points = await controller.getClusterLeaves('earthquakes', clusterId, limit: 100); final children = await controller.getClusterChildren('earthquakes', clusterId); ``` ## Update the data Replace the data of a GeoJSON source without removing its layers: ```dart await style.sources.updateGeoJsonData('points', .text(geoJsonString)); await style.sources.updateGeoJsonUrl('points', 'https://example.com/data.geojson'); ``` Large updates don't block the UI thread, as the map prepares the data in the background (not on web). --- Source: https://maplibre.org/flutter-maplibre/docs/sources/tiles.md # Tile Sources Tile sources load the map data in tiles, only for the area and zoom level on screen. The most common way to use a tile source is by a URL. This can either be - the direct URL of a tile server, e.g. `https://example.com/{z}/{x}/{y}.mvt`, with the `.tiles` constructor of a tile source - the URL of a [TileJSON](https://github.com/mapbox/tilejson-spec) that provides a tile server with additional metadata, e.g. `https://example.com/tiles.json`, with the `.url` constructor - a [PMTiles](#pmtiles) archive, with `pmtiles://` in front of its URL and the `.url` constructor ## PMTiles A [PMTiles](https://docs.protomaps.com/pmtiles/) archive holds all tiles of a tileset in one file. Pass its URL with `pmtiles://` in front to the `.url` constructor of a `VectorSource`, `RasterSource` or `RasterDemSource`, or use it as the `url` of a source in a style JSON. The archive replaces the TileJSON, so don't use the `.tiles` constructor for it. For a `RasterDemSource`, set the `encoding` that the archive's terrain tiles use, for example `RasterDemTerrariumEncoding()` for Terrarium tiles; the default is Mapbox Terrain RGB. ```dart await style.sources.add( const VectorSource.url( id: 'protomaps', url: 'pmtiles://https://example.com/tiles.pmtiles', ), ); ``` - **Android, iOS, macOS, Windows and Linux**: the map reads PMTiles itself. Use `pmtiles://https://…` (or `http://`) for a remote archive and `pmtiles://file:///absolute/path/tiles.pmtiles` for a file on the device. - **Web**: the plugin loads PMTiles together with MapLibre GL JS, see [Setup](https://maplibre.org/flutter-maplibre/docs/getting-started/platforms.md#web) to pin or self-host its version. Use `pmtiles://https://…` or `pmtiles://http://…`; a browser can't read local files, and blocks `http://` archives on a page served over `https://`. The server must answer HTTP range requests, since the map reads only the parts of the archive it needs. On web, it must also send CORS headers. ## MBTiles The map also reads [MBTiles](https://github.com/mapbox/mbtiles-spec) files on the device, but not on web. Pass `mbtiles://` followed by the absolute path of the file to the `.url` constructor, for example `mbtiles:///data/tiles.mbtiles`. MBTiles are not supported on web. ## Raster Tiles The [RasterSource](https://pub.dev/documentation/maplibre/latest/maplibre/RasterSource-class.html) can be used to add a raster tile server. Raster tiles are images that are positioned in a grid next to each other on the map. They are hosted on a tile server that follows the format `z/x/y.png` or any other image file extension. A common use case is to display a satellite map using a [RasterStyleLayer](https://maplibre.org/flutter-maplibre/docs/style-layers.md#raster). ## Raster DEM Tiles Raster DEM tiles are similar to regular [raster tiles](#raster-tiles) but are used in the [HillshadeStyleLayer](https://maplibre.org/flutter-maplibre/docs/style-layers.md#hillshade) to display elevation. Use the [RasterDemSource](https://pub.dev/documentation/maplibre/latest/maplibre/RasterDemSource-class.html) for it. ## Vector Tiles Last but not least you can use the [VectorSource](https://pub.dev/documentation/maplibre/latest/maplibre/VectorSource-class.html) to supply the map with a source of Mapbox Vector Tiles (MVT). The data is then shown in a combination of circle, fill, line and symbol layers on the map. ## MapLibre Tiles (MLT) A vector source can also serve [MapLibre Tiles](https://maplibre.org/maplibre-tile-spec/) instead of MVT. Set `"encoding": "mlt"` on the source in the style JSON. Encoders such as [Martin](https://maplibre.org/martin/) compress integers with FastPFOR. Create the map with `fastPforEnabled` to decode them; without it, such tiles are dropped with the warning `MLT parse failed: FastPFOR decoding is not enabled`. It is not needed on web, where FastPFOR decoding is always enabled. ```dart MapLibreMap( options: MapOptions( style: MapStyle.url('https://example.com/style-with-mlt.json'), fastPforEnabled: true, ), ) ``` ## Update tiles Change the tiles of a source with `style.sources.updateTiles` or `style.sources.updateTileJsonUrl`. Not on web, they remove the layers that use the source and add them back at their positions in one frame, as the map can't change them in place there. --- Source: https://maplibre.org/flutter-maplibre/docs/sources/media.md # Image and Video Sources Image and video sources place one image or video at four coordinates on the map. Show them with a [`RasterStyleLayer`](https://maplibre.org/flutter-maplibre/docs/style-layers.md#raster). ## Image Use the [ImageSource](https://pub.dev/documentation/maplibre/latest/maplibre/ImageSource-class.html) if you want to render an image on the map. `ImageSource.url` loads the image from a URL, `ImageSource.bytes` takes an encoded image such as a PNG, and `ImageSource.provider` takes any Flutter `ImageProvider`, for example an `AssetImage` or a `FileImage`. ```dart await style.sources.add( const ImageSource.provider( id: 'radar', image: AssetImage('assets/radar.png'), coordinates: LngLatQuad( topLeft: Geographic(lon: -80.425, lat: 46.437), topRight: Geographic(lon: -71.516, lat: 46.437), bottomRight: Geographic(lon: -71.516, lat: 37.936), bottomLeft: Geographic(lon: -80.425, lat: 37.936), ), ), ); ``` An example use case is to position a weather radar image on the map. Move the image with `style.sources.updateImageCoordinates('radar', coordinates)`. ## Video Likewise, the [VideoSource](https://pub.dev/documentation/maplibre/latest/maplibre/VideoSource-class.html) can be used to render a video on the map, from URLs with `VideoSource.urls`, encoded video bytes with `VideoSource.bytes` or a Flutter asset with `VideoSource.asset`. The video source is only supported on web. --- Source: https://maplibre.org/flutter-maplibre/docs/style-layers.md # Style Layers Style layers draw the data of a [source](https://maplibre.org/flutter-maplibre/docs/sources.md) on the map. They are the layers of the [MapLibre style spec](https://maplibre.org/maplibre-style-spec/layers/), with every paint and layout property as a typed parameter. Use them for data that [annotation layers](https://maplibre.org/flutter-maplibre/docs/annotations.md) don't cover, or for large data sets, as the map styles the features itself. Add a source and a layer that uses it once the style has loaded: ```dart linenums="1" hl_lines="6-15" @override Widget build(BuildContext context) { return MapLibreMap( options: MapOptions(initCamera: .position(center: Geographic(lon: 9.17, lat: 47.68), zoom: 7)), onStyleLoaded: (style) async { await style.sources.add( const GeoJsonSource.url( id: 'earthquakes', url: 'https://maplibre.org/maplibre-gl-js/docs/assets/earthquakes.geojson', ), ); await style.layers.add( CircleStyleLayer(id: 'earthquakes', sourceId: 'earthquakes'), ); }, ); } ``` `style.layers` also holds the layers of the loaded style. Read them by id, change their properties, move or remove them: ```dart final roads = style.layers['roads']; roads?.visible = false; style.layers.move('route', belowLayerId: 'labels'); await style.layers.remove('earthquakes'); ``` See [Paint & Layout](https://maplibre.org/flutter-maplibre/docs/style-layers/paint-and-layout.md) for the properties, [Expressions](https://maplibre.org/flutter-maplibre/docs/style-layers/expressions.md#layers-on-the-map) for updates at runtime and [Click and Hover](https://maplibre.org/flutter-maplibre/docs/style-layers/click-and-hover.md) for events on the features of a layer. ## Circle [![Circle Style Layer](https://maplibre.org/flutter-maplibre/assets/images/layers/circle_layer.jpg)](https://maplibre.org/flutter-maplibre/demo/#/style-layers/circle) A `CircleStyleLayer` draws a circle for each point. Use it for point data such as measurements or events. ```dart await style.layers.add( CircleStyleLayer( id: 'earthquakes', sourceId: 'earthquakes', radius: const .literal(6), color: const .literal(Colors.red), ), ); ``` See the [example app](https://github.com/maplibre/flutter-maplibre/blob/main/examples/lib/style_layers_circle_page.dart). ## Fill [![Fill Style Layer](https://maplibre.org/flutter-maplibre/assets/images/layers/fill_layer.jpg)](https://maplibre.org/flutter-maplibre/demo/#/style-layers/fill) A `FillStyleLayer` fills polygons, optionally with an outline. ```dart final geojson = await rootBundle.loadString('assets/geojson/lake-constance.json'); await style.sources.add( GeoJsonSource.data(id: 'lake', data: .text(geojson)), ); await style.layers.add( FillStyleLayer( id: 'lake', sourceId: 'lake', color: const .literal(Color(0xFF429EF5)), ), ); ``` See the [example app](https://github.com/maplibre/flutter-maplibre/blob/main/examples/lib/style_layers_fill_page.dart). ## Fill Extrusion [![Fill Extrusion Style Layer](https://maplibre.org/flutter-maplibre/assets/images/layers/fill_extrusion_layer.jpg)](https://maplibre.org/flutter-maplibre/demo/#/style-layers/fill-extrusion) A `FillExtrusionStyleLayer` extrudes polygons to 3D shapes, such as buildings. Tilt the map to see their height. ```dart await style.sources.add( const GeoJsonSource.url( id: 'rooms', url: 'https://maplibre.org/maplibre-gl-js/docs/assets/indoor-3d-map.geojson', ), ); await style.layers.add( FillExtrusionStyleLayer( id: 'rooms', sourceId: 'rooms', color: .get('color').convertToColor(), height: .get('height').asNumber(), base: .get('base_height').asNumber(), opacity: const .literal(0.5), ), ); ``` See the [example app](https://github.com/maplibre/flutter-maplibre/blob/main/examples/lib/style_layers_fill_extrusion_page.dart). ## Heatmap [![Heatmap Style Layer](https://maplibre.org/flutter-maplibre/assets/images/layers/heatmap_layer.jpg)](https://maplibre.org/flutter-maplibre/demo/#/style-layers/heatmap) A `HeatmapStyleLayer` shows the density of points as a color gradient. ```dart await style.layers.add( HeatmapStyleLayer(id: 'earthquakes-heat', sourceId: 'earthquakes'), ); ``` See the [example app](https://github.com/maplibre/flutter-maplibre/blob/main/examples/lib/style_layers_heatmap_page.dart). ## Hillshade [![Hillshade Style Layer](https://maplibre.org/flutter-maplibre/assets/images/layers/hillshade_layer.jpg)](https://maplibre.org/flutter-maplibre/demo/#/style-layers/hillshade) A `HillshadeStyleLayer` shades terrain from the elevation tiles of a [`RasterDemSource`](https://maplibre.org/flutter-maplibre/docs/sources/tiles.md#raster-dem-tiles). ```dart await style.sources.add( const RasterDemSource.url( id: 'terrain', url: 'https://demotiles.maplibre.org/terrain-tiles/tiles.json', tileSize: 256, ), ); await style.layers.add( HillshadeStyleLayer( id: 'hillshade', sourceId: 'terrain', shadowColor: const .literal([Color(0xFF473B24)]), ), ); ``` `ColorReliefStyleLayer` colors the same tiles by elevation. See the [example app](https://github.com/maplibre/flutter-maplibre/blob/main/examples/lib/style_layers_hillshade_page.dart). ## Line [![Line Style Layer](https://maplibre.org/flutter-maplibre/assets/images/layers/line_layer.jpg)](https://maplibre.org/flutter-maplibre/demo/#/style-layers/line) A `LineStyleLayer` draws lines and the outlines of polygons, such as routes, roads or borders. ```dart final geojson = await rootBundle.loadString('assets/geojson/path.json'); await style.sources.add( GeoJsonSource.data(id: 'path', data: .text(geojson)), ); await style.layers.add( LineStyleLayer( id: 'path', sourceId: 'path', color: const .literal(Color(0xFFFF0000)), width: const .literal(3), ), ); ``` See the [example app](https://github.com/maplibre/flutter-maplibre/blob/main/examples/lib/style_layers_line_page.dart). ## Raster [![Raster Style Layer](https://maplibre.org/flutter-maplibre/assets/images/layers/raster_layer.jpg)](https://maplibre.org/flutter-maplibre/demo/#/style-layers/raster) A `RasterStyleLayer` shows the image tiles of a [`RasterSource`](https://maplibre.org/flutter-maplibre/docs/sources/tiles.md#raster-tiles), such as satellite imagery, or an [image source](https://maplibre.org/flutter-maplibre/docs/sources/media.md). ```dart await style.sources.add( const RasterSource.tiles( id: 'osm', tiles: ['https://tile.openstreetmap.org/{z}/{x}/{y}.png'], maxZoom: 20, tileSize: 256, attribution: 'Β© OpenStreetMap contributors', ), ); await style.layers.add(RasterStyleLayer(id: 'osm', sourceId: 'osm')); ``` See the [example app](https://github.com/maplibre/flutter-maplibre/blob/main/examples/lib/style_layers_raster_page.dart). ## Symbol [![Symbol Style Layer](https://maplibre.org/flutter-maplibre/assets/images/layers/symbol_layer.jpg)](https://maplibre.org/flutter-maplibre/demo/#/style-layers/symbol) A `SymbolStyleLayer` draws icons and text labels. Add the icon image to the style first: ```dart final response = await http.get(Uri.parse(imageUrl)); await style.addImage('marker', response.bodyBytes); await style.layers.add( SymbolStyleLayer( id: 'images', sourceId: 'points', iconImage: const .literal('marker'), iconSize: const .literal(0.08), iconAnchor: const .literal(IconAnchor.bottom), ), ); ``` See the [example app](https://github.com/maplibre/flutter-maplibre/blob/main/examples/lib/style_layers_symbol_page.dart). ## Background A `BackgroundStyleLayer` fills the whole map with a color or a pattern. It has no source. ```dart await style.layers.add( BackgroundStyleLayer(id: 'background', color: const .literal(Colors.white)), ); ``` --- Source: https://maplibre.org/flutter-maplibre/docs/style-layers/paint-and-layout.md # Paint & Layout Properties [Style Layers](https://maplibre.org/flutter-maplibre/docs/style-layers.md) have every paint and layout property of the style spec, while the [annotation layers](https://maplibre.org/flutter-maplibre/docs/annotations.md) have a selection of them. See the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/layers) for all available properties for the different layers. Every property is an optional parameter and a getter and setter of its layer class, without the prefix of the layer type, so `line-width` is `LineStyleLayer.width`. It takes an [Expression](https://maplibre.org/flutter-maplibre/docs/style-layers/expressions.md) for zoom level dependent and data driven styling. A property with a transition also has one, such as `colorTransition`: ```dart final layer = LineStyleLayer( id: 'route', sourceId: 'route', width: const .literal(4), cap: const .literal(LineCap.round), colorTransition: const StyleTransition(duration: Duration(milliseconds: 500)), ); ``` `Expression.raw` takes the JSON of a single property, and `StyleLayer.fromJson` the JSON of a whole layer, for example one copied from a style. Expressions can be a bit tricky. In case you are not experienced, it is recommended to build and test them in [Maputnik](https://maplibre.org/maputnik) first and copy them over. [![Maputnik Paint Properties](https://maplibre.org/flutter-maplibre/assets/images/maputnik-paint.jpg)](https://maplibre.org/maputnik) --- Source: https://maplibre.org/flutter-maplibre/docs/style-layers/expressions.md # Expressions Every property of a style layer is an `Expression`, where `T` is the Dart type it evaluates to: `num`, `String`, `bool`, `Color`, `Offset`, a `List` or a spec enum like `LineCap`. A constant is `.literal(x)`; anything else is computed by the map from the feature, the zoom level and more. See the [expressions of the style spec](https://maplibre.org/maplibre-style-spec/expressions/) for what each one does. ```dart final layer = CircleStyleLayer( id: 'quakes', sourceId: 'quakes', filter: .all([ .greaterThan(.get('mag').asNumber(), .literal(5)), .has('place'), ]), radius: .interpolate(.exponential(2), .zoom(), { 5: .literal(2), 10: .literal(8), }), color: .match( .get('type'), {'major': const .literal(Color(0xFFFF0000))}, fallback: const .literal(Color(0xFF888888)), ), ); ``` Dot shorthands need a parameter type to resolve against, so they don't work as operands of an operator. Start with `Expression.` there: `Expression.get('mag').asNumber() > .literal(5)`. ## Names Spec names are kept, except where they clash with Dart keywords or members: | Spec | Dart | |---|---| | `case` | `Expression.select([(test, output), …], fallback: …)` | | `in` | `list.contains(item)`, `string.contains(substring)` | | `let` / `var` | `Expression.withVariable(name, value, (v) => … v.use() …)` | | `!` | `expression.not()` | | `==`, `!=` | `Expression.equal(a, b)`, `Expression.notEqual(a, b)` | | `>`, `<`, `>=`, `<=` | `Expression.greaterThan(a, b)` and so on, or the operators on number and string expressions | | `+`, `-`, `*`, `/`, `%` | operators on number expressions; `+` on string expressions is `concat` | | `^` | `base.pow(exponent)` | | `typeof` | `expression.type()` | | `string`, `number`, `boolean`, `object`, `array` | `asString()`, `asNumber()`, `asBoolean()`, `asObject()`, `asArray()` | | `to-string`, `to-number`, `to-boolean`, `to-color` | `convertToString()`, `convertToNumber()`, `convertToBoolean()`, `convertToColor()` | Untyped values such as `.get('x')` are `Expression`. Assert their type before use with `asNumber()` and the like, or change only the static type with `cast()`. `Expression.raw(['get', 'x'])` takes the JSON of the style spec, for anything not covered. ## Layers on the map A layer you added, or one from `style.layers`, is its own controller. Its setters update the map without waiting for it, in order, so an animation can call them every frame: ```dart final line = style.layers['route']! as LineStyleLayer; line.width = const .literal(4); line.visible = false; line.width = null; // back to the default line.moveBelow('labels'); ``` Getters return the value that is set or the default of the spec. A constant reads back as a `Literal`: ```dart if (line.width case Literal(:final value)) print(value); ``` Everything else reads back as an `Expression.raw`. Removing the layer or loading a new style detaches the object; its setters then only change the object. A property with a transition has a typed one next to it, such as `line.colorTransition = const StyleTransition(duration: Duration(seconds: 1))`. To show several changes in one frame on every platform but web, use a batch. The callback must be synchronous: ```dart style.batch(() { line.visible = true; style.layers.move('route', belowLayerId: 'labels'); }); ``` --- Source: https://maplibre.org/flutter-maplibre/docs/style-layers/click-and-hover.md # Click and Hover Style layers with vector features report taps and the mouse on their features while they are on a map: - `onClick`: the user tapped or clicked a feature of the layer. - `onEnter`: a mouse or stylus moved onto a feature of the layer. - `onLeave`: the mouse or stylus left the feature that `onEnter` reported. Set them as constructor parameters of a layer you add, or on a layer of the loaded style: ```dart linenums="1" Future _onStyleLoaded(StyleController style) async { await style.sources.add( const GeoJsonSource.url(id: 'states', url: 'https://example.com/states.geojson'), ); await style.layers.add( FillStyleLayer( id: 'states', sourceId: 'states', onClick: (event) => print(event.feature.properties['name']), ), ); // A layer that came with the style. final roads = style.layers['roads']; roads?.onEnter = (event) => setState(() => _road = event.feature); roads?.onLeave = (event) => setState(() => _road = null); } ``` ## Details - Each `StyleLayerFeatureEvent` holds the topmost `RenderedFeature` of the layer under the pointer, and where the pointer is as `point` and `screenPoint`. - Every layer under a tap reports it, not only the topmost one, like gl-js `map.on('click', layerId, ...)`. `MapLibreMap.onClick` is called as well. - Features with an id are told apart: moving from one onto another reports `onLeave` for the first and `onEnter` for the second. A layer of features without ids reports entering and leaving its features as a whole. - Removing the layer or loading a new style ends the calls. - `CircleStyleLayer`, `FillStyleLayer`, `FillExtrusionStyleLayer`, `HeatmapStyleLayer`, `LineStyleLayer` and `SymbolStyleLayer` report them. - Touches don't hover, so `onEnter` and `onLeave` are only called for mice and styluses. - For annotation layers, see [annotations: click and hover](https://maplibre.org/flutter-maplibre/docs/annotations/click-and-hover.md). --- Source: https://maplibre.org/flutter-maplibre/docs/contributing/architecture.md # Architecture `maplibre` is a [federated plugin](https://docs.flutter.dev/packages-and-plugins/developing-packages#federated-plugins) with two implementations: `maplibre_web` uses MapLibre GL JS in the browser, and `maplibre_native` uses MapLibre Native through its C API on every other platform. Both implement the same interface, so apps only use `maplibre`. ## Packages ```mermaid flowchart TB App(["Your app"]) Geo["maplibre_geolocator (optional)
geolocator positions β†’ UserLocation"] Main["maplibre
annotation layers, UI widgets,
WidgetLayer, UserLocationLayer"] PI["maplibre_platform_interface
MapLibreMap, MapController, StyleController,
style.layers, style.sources, expressions,
MapGestureDetector, OfflineManager"] Web["maplibre_web
MapLibreMapStateWeb"] Native["maplibre_native
MapLibreMapStateNative"] GLJS[("MapLibre GL JS
loaded from a CDN")] FFI[("maplibre_native_ffi
MapLibre Native C API")] App --> Main App -.-> Geo Geo -.-> Main Main --> PI PI -- "web" --> Web PI -- "Android, iOS, macOS,
Windows, Linux" --> Native Web -- "js_interop" --> GLJS Native -- "dart:ffi" --> FFI ``` | Package | Content | |-------------------------------|-------------------------------------------------------------------------------------------------------------| | `maplibre` | What apps import: the annotation layers, UI widgets, `WidgetLayer` and `UserLocationLayer`, and everything of the platform interface. | | `maplibre_platform_interface` | `MapLibreMap`, the `MapController` and `StyleController` interfaces, `MapLibreMapState`, the style layers, sources and expressions, the `OfflineManager` interface and the gesture recognizer. | | `maplibre_web` | `MapLibreMapStateWeb`: binds MapLibre GL JS with `js_interop` and loads it on the first map. | | `maplibre_native` | `MapLibreMapStateNative`: drives MapLibre Native through `maplibre_native_ffi` and shows its frames in a Flutter texture. | | `maplibre_geolocator` | Turns `geolocator` positions into the `UserLocation` stream of a `UserLocationLayer`. | ## Map widget `MapLibreMap` creates the `MapLibreMapState` of the platform. The state is the `MapController` of the map, and builds the same tree on every platform: ```mermaid flowchart TB Map["MapLibreMap"] --> State["MapLibreMapState
(implements MapController)"] State --> Stack["Stack"] Stack --> Gest["MapGestureDetector"] Gest --> Platform["Platform widget
Texture (native) or HtmlElementView (web)"] Stack --> Children["MapLibreMap.children
UI widgets, WidgetLayer, UserLocationLayer"] State -. "diffs MapLibreMap.layers" .-> LM["LayerManager"] LM -. "adds, updates, removes" .-> SL["style.sources, style.layers"] ``` - **Gestures** are recognized once, in `MapGestureDetector`, for every platform. It hands screen-space camera steps to a `GestureCameraSink`, which each platform implements with its own camera engine. Widgets in `children` sit above it, so they receive their own pointers first. - **Annotation layers** in `MapLibreMap.layers` are turned into GeoJSON sources and style layers by the `LayerManager`, which only updates what changed between builds. - **Style changes** go through `style.layers` and `style.sources`. They keep the state of the style in Dart, so reads are synchronous, and pass changes to the platform through a small `StyleBackend` interface. ## Native rendering On Android, iOS, macOS, Windows and Linux, MapLibre Native renders each map off screen into a GPU texture, and Flutter shows it with a `Texture` widget. Maps therefore compose with other widgets like any other part of the widget tree. ```mermaid flowchart TB State["MapLibreMapStateNative"] Renderer["MapRenderer
asks for frames when the map changes"] Target["FrameTarget
one per platform"] C[("MapLibre Native C API
native asset of maplibre_native_ffi")] Plugin["Platform plugin and GPU texture
Windows: Vulkan β†’ D3D11
Linux: Vulkan β†’ OpenGL
Android: OpenGL ES or Vulkan β†’ SurfaceProducer
iOS, macOS: Metal β†’ IOSurface"] Tex["Flutter Texture widget"] State --> Renderer Renderer -- "dart:ffi" --> C Renderer --> Target C -- "renders frames into" --> Plugin Target -- "ffigen / jnigen:
hands over each frame" --> Plugin Plugin -- "texture registry" --> Tex ``` 1. `MapRenderer` owns the map and its render session in the C library, and asks for a frame whenever the map changed. 2. MapLibre Native renders the frame on its own thread into the render target of the platform. 3. The `FrameTarget` of the platform hands the frame to its plugin, which marks the Flutter texture as updated. Where the platform allows it, the frame is shared with Flutter on the GPU, without a CPU copy. The C library and its Dart binding come from [maplibre_native_ffi](https://pub.dev/packages/maplibre_native_ffi). Its build hook downloads the prebuilt library for each target. Dart calls the platform plugins through bindings generated with ffigen (C) and jnigen (Kotlin). All maps and the `OfflineManager` share one database for the cache and the offline regions. ## Web rendering On web, `MapLibreMapStateWeb` creates a MapLibre GL JS map in a `div` and shows it with an `HtmlElementView`. MapLibre GL JS's own gesture handling is turned off, and the shared `MapGestureDetector` moves its camera instead. On first use, the plugin loads MapLibre GL JS and PMTiles from a CDN, unless the page already loaded them. --- Source: https://maplibre.org/flutter-maplibre/docs/contributing/development.md # Local development This page explains how to work on the packages themselves. To use the packages in your app, read [Installation](https://maplibre.org/flutter-maplibre/docs/getting-started/setup.md). ## Get started The repository is a [pub workspace](https://dart.dev/tools/pub/workspaces), so one `flutter pub get` in its root resolves every package. You need Flutter 3.47 or newer: ```bash git clone https://github.com/maplibre/flutter-maplibre cd flutter-maplibre flutter pub get cd examples flutter run -d windows # or macos, linux, chrome, an iOS simulator or an Android device ``` | Path | Content | |-----------------------------------------|--------------------------------------------------------| | `packages/maplibre` | The app-facing package | | `packages/maplibre_platform_interface` | The shared API, style classes and gesture recognizer | | `packages/maplibre_web` | The web implementation on MapLibre GL JS | | `packages/maplibre_native` | The implementation for every other platform | | `packages/maplibre_geolocator` | The `geolocator` adapter for `UserLocationLayer` | | `examples` | The example app, which also runs the integration tests | | `website` | This documentation | See [Architecture](https://maplibre.org/flutter-maplibre/docs/contributing/architecture.md) for how the packages fit together. ## Tests ```bash # Unit tests, inside a package flutter test # Integration tests on a device cd examples && flutter test integration_test/all_test.dart -d windows ``` ## Before you commit ```bash dart format . dart analyze --fatal-warnings --fatal-infos ``` ## More [CONTRIBUTING.md](https://github.com/maplibre/flutter-maplibre/blob/main/CONTRIBUTING.md) covers building the MapLibre Native C library locally, and [AGENTS.md](https://github.com/maplibre/flutter-maplibre/blob/main/AGENTS.md) lists the code generation commands and the rules of the code base. --- Source: https://maplibre.org/flutter-maplibre/docs/contributing/api-guidelines.md # API guidelines These rules shape the public API of `maplibre` and `maplibre_platform_interface`. They explain why the API looks the way it does, so that new features fit in, and they help plugin authors write packages that feel like part of `maplibre`. The reasons behind single features are recorded in [`.agents/decisions/`](https://github.com/maplibre/flutter-maplibre/tree/main/.agents/decisions), one file per area. If a change needs to break one of these rules, discuss it in an issue first. ## Declarative widgets, imperative style `maplibre` has two kinds of API, and each feature belongs to exactly one of them. **Widgets are declarative.** `MapLibreMap`, its `MapOptions`, the [annotation layers](https://maplibre.org/flutter-maplibre/docs/annotations.md) in `layers`, the [plugins](https://maplibre.org/flutter-maplibre/docs/plugins.md) in `children` and the `on…` callbacks describe what the map should look like now. Apps change them by rebuilding, and the map applies only what changed. - A widget parameter has no controller method that changes the same thing. A new style is a new `MapOptions.style`, so there is no `setStyle`. - Options that apps set once and rarely change, such as `initCamera`, say so in their name or docs. **The style is imperative.** [Sources](https://maplibre.org/flutter-maplibre/docs/sources.md) and [style layers](https://maplibre.org/flutter-maplibre/docs/style-layers.md) are added, changed, moved and removed through the `StyleController`, `style.sources` and `style.layers`, usually in `onStyleLoaded`. They are objects with an identity on the map, and apps change them often, so they don't go through a rebuild. - Never add a declarative option for style layers or sources to `MapLibreMap`. Events of a style layer are fields of the layer (`onClick`, `onEnter`, `onLeave`), not a `layerEvents` map on the widget. - Annotation layers are built on style layers, but keep their own small, declarative API. ```dart // Do: a declarative parameter, changed with setState() MapLibreMap( options: MapOptions(style: .url(styleUrl)), layers: [CircleLayer(points: points)], ); // Do: imperative style changes onStyleLoaded: (style) async { await style.sources.add(GeoJsonSource.url(id: 'quakes', url: quakesUrl)); await style.layers.add(CircleStyleLayer(id: 'quakes', sourceId: 'quakes')); }, // Don't: declarative style layers or a setter for a widget parameter MapLibreMap(styleLayers: [CircleStyleLayer(...)]); controller.setStyle(styleUrl); ``` ## Types that may grow Use a `sealed` class with `const` named factory constructors when a value can take one of several forms. The factories read well with Dart's dot shorthands, and a new form is a new constructor. | Type | Variants | |------------------|-------------------------------------------------------------| | `MapStyle` | `.url`, `.json`, `.asset`, `.file` | | `CameraUpdate` | `.position`, `.bounds`, `.points`, `.geometry` | | `CameraAnimation`| `.ease`, `.fly` | | `QueryGeometry` | `.point`, `.rect`, `.viewport` | | `GeoJsonData` | `.featureCollection`, `.feature`, `.geometry`, `.json`, `.text` | | `MarkerIcon` | `.iconData`, `.asset`, `.bytes`, `.provider`, `.named`, `.expression` | - Adding a subclass to a sealed class is not a breaking change when apps create one instance and pass it in (`CameraUpdate`, `QueryGeometry`) or get one at a time (`MapEvent`). - Prefer one parameter of a sealed type over several parameters that exclude each other. A marker has one `icon`, not `icon` and `iconImage`. - Group related switches into an option class whose fields are optional and on by default, with a `.none()` constructor, such as `MapMovements` and `MapGestures`. A new switch is a new optional field. ```dart // Do controller.animateCamera( .position(center: center, zoom: 12), animation: const .fly(), ); // Don't: parameters that exclude each other, or a mode flag controller.animateCamera(center: center, bounds: bounds, fly: true); ``` ## Style layers are their own controllers Like the layers of the Android and iOS SDKs, a style layer object controls its layer on the map. - Every property of the style spec is a typed getter, setter and optional constructor parameter, generated from the spec. There are no `paint` or `layout` maps and no access by property name. - Getters are synchronous and read the state that Dart holds. Setters are synchronous too and send the change to the map in order, without a `Future`. There are no async `setX` methods. - Properties take a typed `Expression`, with `const .literal(…)` for constants, so the same parameter takes a constant, a zoom curve or a value per feature. ```dart // Do final layer = style.layers['route'] as LineStyleLayer?; layer?.width = const .literal(6); // Don't await controller.setLayerProperty('route', 'line-width', 6); ``` ## Sync and async A member is synchronous when Dart holds the answer: the style layers and sources, the current `camera`, the options. It returns a `Future` when a platform has to answer, such as feature queries, `cameraFor`, `toLngLat` and camera animations. An animation completes with a result (`CameraAnimationResult`) instead of throwing when a gesture cancels it. ## Events - One `on…` callback per event on `MapLibreMap` and `MapPlugin`, each with an event class of its own, such as `onClick` with `MapEventClick`. Not one `onEvent` with a type switch. A new event is a new optional callback. - A callback that is null is not subscribed: the map doesn't listen for it. - Events with a default action, such as double click zoom or drag pan, have `preventDefault()` on the event. ## Plugins and UI widgets - Build features that sit on the map as widgets for `MapLibreMap.children`. `MapPlugin` gives them the declarative parameters of `MapLibreMap` (layers, callbacks, movements and gestures), and `MapController.of`, `CameraPosition.of`, `MapOptions.of` and `StyleController.of` give them the map's state. A widget that moves with the camera reads `CameraPosition.of`. - The packages depend on `flutter/widgets` only, never on Material or Cupertino, so apps with any design system can use them. - UI widgets don't read a `Theme`. They have default values for their look and take parameters such as `backgroundColor`, `needleColor` or `textStyle` to change it. ## One API for every platform - A feature exists once, for every platform. There are no parameters or classes prefixed with a platform (`androidX`, `webX`). - A feature needs a way to work on every platform before it is added: on web through MapLibre GL JS, everywhere else through the C API of `maplibre_native_ffi`. - When a platform can't support something, document it, and fail in a documented way, for example with an `UnsupportedError`. - Use the types of [geobase](https://pub.dev/packages/geobase) for geographic data: `Geographic` for positions, `GeoBox` for bounds, `Feature` and `Geometry` for features. `maplibre` re-exports the ones its API uses. ## Platform conversions Convert between the types of this plugin and those of a platform (`mln.*`, gl-js interop types) with extension methods in the platform package's `lib/src/extensions.dart`, not with static or top-level helpers or members of interop types. - Name an extension `Ext`, or `MlnExt` and `JsExt` on platform types. - Convert with `toMln()` or `toJs()`, and back with `to()`. ```dart // Do extension GeographicExt on Geographic { mln.LatLng toMln() => mln.LatLng(latitude: lat, longitude: lon); } extension MlnLatLngExt on mln.LatLng { Geographic toGeographic() => Geographic(lon: longitude, lat: latitude); } // Don't mln.LatLng _latLngOf(Geographic position) => ...; ``` ## Documentation - Every public member has a dartdoc comment that starts with one sentence saying what it does. - Name platforms, never the engine behind them: write "only on web", "not on web" or a list of platforms, not "on MapLibre Native" or "native maps". - Don't mark features as experimental, and don't add status columns. A feature is either part of the API or not. - Show new features in the example app and document them on this website. ## Compatibility `maplibre` follows [semantic versioning](https://dart.dev/tools/pub/versioning): while it is below 1.0, a new minor version (0.3 to 0.4) is a breaking release. - Breaking releases come with a migration guide, such as [Upgrade to 0.4](https://maplibre.org/flutter-maplibre/docs/migrate/upgrade-from-v0.3.x.md), that names the replacement of every removed or changed API. - Every user-facing change gets one short bullet in the changelog of `packages/maplibre`. --- Source: https://maplibre.org/flutter-maplibre/features.md # Supported Features This page gives an overview of the functionality that is available on each platform. Android, iOS, macOS, Windows and Linux share one implementation. ### General Functionality | Feature | Web | Android | iOS | Windows | macOS | Linux | |---------------|-----|---------|-----|---------|-------|-------| | Map | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | MapController | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | Offline | ❌ | βœ… | βœ… | βœ… | βœ… | βœ… | | Events | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | Annotations | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | Widget Layer | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | User Location | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | Paused Rendering | βž– | βœ… | βœ… | βœ… | βœ… | βœ… | | Globe Projection | βœ… | ❌ | ❌ | ❌ | ❌ | ❌ | | MBTiles | ❌ | βœ… | βœ… | βœ… | βœ… | βœ… | | PMTiles | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | ### Layers | Feature | Web | Android | iOS | Windows | macOS | Linux | |----------------------|-----|---------|-----|---------|-------|-------| | Background Layer | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | Circle Layer | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | Fill Layer | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | Fill Extrusion Layer | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | Heatmap Layer | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | Hillshade Layer | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | Line Layer | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | Raster Layer | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | Symbol Layer | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | Color Relief Layer | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | ### Sources | Feature | Web | Android | iOS | Windows | macOS | Linux | |----------------|-----|---------|-----|---------|-------|-------| | GeoJSON Source | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | Image Source | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | Video Source | βœ… | ❌ | ❌ | ❌ | ❌ | ❌ | | Raster Source | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | Raster DEM Source | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | Vector Source | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | ### User Gestures | Feature | Web | Android | iOS | Windows | macOS | Linux | |-----------------|-----|---------|-----|---------|-------|-------| | click | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | double click | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | secondary click | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | long click | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | pan, pinch zoom, twist, tilt | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | scroll wheel zoom | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | mouse rotate and tilt | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | ### Programmatic Control | Feature | Web | Android | iOS | Windows | macOS | Linux | |----------------------------------------|-----|---------|-----|---------|-------|-------| | Move Map Camera | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | Animate Map Camera | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | Add or remove a Map Source | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | Add or remove a Map Layer | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | Show the User Location | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | Track the User Location | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | Convert Coordinates to Screen Position | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | Convert Screen Position to Coordinates | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | Get Meters per Pixel | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | Get the currently visible Region | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | | Query rendered Features | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… | βž– On web, the browser already skips hidden maps, so `MapLibreMap.paused` has no effect there.