Flutter and Mapbox: Deploy and display vector data via Mapbox Tilesets and Expressions
When developing an outdoor app with specific cartography data, you may encounter challenges in efficiently deploying data on your map. This article explores an alternative way to present data using MapBox tilesets, ensuring smooth performance and on-demand data details.
The Problem You Can Encounter
My experience is made while working on Camino Love, application for pilgrims with hundreds of pilgrimage routes across the Europe. We haven’t thought about such scale from the very beginning which leads us to the poor map performance. We haven’t researched vector data sources as much as possible.
To achieve smooth map performance in you Flutter app, you could use MapBox tilesets (as a CMS system) and mapbox_maps_flutter plugin (the official MapBox plugin)
Creating a Tileset in MapBox
To get started, you need to create a tileset in MapBox. Here’s a step-by-step guide:
- Prerequisites
- A MapBox account with public and secret keys
- An authenticated local machine
- Your data in a vector format (e.g., GPX, KML, GeoJson). - Upload Data to MapBox:
- Log in to your MapBox account in Mapbox Studio
- Find ‘Tilesets’ section → New Tileset
Adding Source and Layer to the Map
Disclaimer: This part is not a fully described code. Feel free to check the source code or ask anything in the comments :)
Once your tileset is created, you can add it to your map as a vector source and then create a layer to display it.
await mapController.style.addSource(
VectorSource(
id: 'linesgeojson_routes',
url: 'mapbox://your_username.your_tileset_id'
)
);
await mapController.style.addLayer(
LineLayer(
id: 'routes_layer',
sourceId: 'linesgeojson_routes',
sourceLayer: 'linesgeojson', // the source id shown in MapBox Studio
lineWidth: 2.0,
)
);
Styling with Expressions
MapBox expressions allow for dynamic styling of your map layers. You can use expressions to change the appearance of map features based on data properties.
The line data which was added to the map have ‘stroke’ property with a hex color in it. So we could use that in order to display colorful routes on the map.
await controller.style.setStyleLayerProperties(
'routes_layer',
jsonEncode({
'line-color': ['get', 'stroke'],
}),
);
Result
In the result we’ve got a map with the data provided via GeoJson and colored using expressions mechanism
Useful links
Full code example: https://github.com/alex-tifox/mapbox_vector_source_example
Generate your own GeoJson for testing purposes: geojson.io
Mapbox Official Flutter Plugin: https://pub.dev/packages/mapbox_maps_flutter
Mapbox Expressions Reference: https://docs.mapbox.com/style-spec/reference/expressions/
Feedback
Feel free to reach out to me if you have any question of feedback. I’m happy to help you with any issues you might have. Thanks for attention!