Mapbox Maps Flutter SDK

repository·main·Indexed 18 days ago

https://github.com/mapbox/mapbox-maps-flutter

A Flutter SDK for embedding high-performance, customized Mapbox maps into Android and iOS applications. Features include MapWidget for map embedding, MapboxMap controller for camera and style management, annotation managers for points and circles, and support for custom map styles, layers, and expressions. Requires iOS 14+, Android SDK 21+, and Flutter SDK 3.22.3 / Dart SDK 3.4.4 or higher.

Tokens
18.4K
Snippets
48
Records
82
Agent score
62%

What's inside mapbox-maps-flutter

  1. Prerequisites for Mapbox Maps Flutter development

    main

    Ensure your environment meets the following requirements before developing with the SDK:

    • Flutter SDK: 3.27.0 or higher (Dart SDK 3.6.0+)
    • Xcode: Required for iOS (iOS deployment target 14.0+)
    • Android Studio/SDK: API level 21+ and compile SDK 35
    • Mapbox Account: A valid account with access tokens.
  2. Getting started with the Mapbox Maps Flutter SDK example

    main

    The mapbox_maps_example project serves as a functional starting point for developers looking to integrate the Mapbox Maps Flutter SDK into a Flutter application. It demonstrates core SDK capabilities and provides a template for building map-based applications.

    If you are new to Flutter, it is recommended to review the official Flutter documentation, including the 'Write your first Flutter app' codelab and the Flutter Cookbook, before diving into the Mapbox-specific implementation.

  3. Run the Example App with a Public Access Token

    main

    The example app demonstrates SDK features and hosts integration tests. To run it, you must provide your Mapbox public token (pk.*) using the --dart-define flag.

    Via Command Line

    cd example
    flutter run --dart-define=ACCESS_TOKEN=pk.your_token_here

    Via VS Code

    To persist the token in VS Code, add the argument to your .vscode/launch.json configuration.

    {
      "configurations": [
        {
          "args": ["--dart-define", "ACCESS_TOKEN=pk.your_token_here"]
        }
      ]
    }
  4. Add a Map using MapWidget and MapboxMap

    main

    To embed a map, use the MapWidget widget. To interact with the map (control camera, styles, etc.), you must capture the MapboxMap controller instance provided via the onMapCreated callback.

    MapWidget allows customization through MapOptions, CameraOptions, and styleURL. The MapboxMap controller is the primary entry point for most SDK APIs.

    class FullMapState extends State<FullMap> {
      MapboxMap? mapboxMap;
    
      _onMapCreated(MapboxMap mapboxMap) {
        this.mapboxMap = mapboxMap;
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: MapWidget(
            key: ValueKey("mapWidget"),
            onMapCreated: _onMapCreated,
          ),
        );
      }
    }
  5. Configure Mapbox Access Token

    main

    You must configure a Mapbox Access Token to use the SDK. You can set the token globally using MapboxOptions.setAccessToken(ACCESS_TOKEN).

    For better security, it is recommended to pass the token via command-line arguments during build or run, or via launch.json using --dart-define. You can then retrieve it in your Dart code using String.fromEnvironment.

    // Set the token globally
    MapboxOptions.setAccessToken(ACCESS_TOKEN);
    
    // Retrieve from environment
    String ACCESS_TOKEN = String.fromEnvironment("ACCESS_TOKEN");
  6. Configure Location Permissions

    main

    To use the user location component, you must request permissions at runtime (e.g., using permission_handler) and declare them in your platform-specific configuration files.

    Android

    Add these to your AndroidManifest.xml:

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

    iOS

    Add the NSLocationWhenInUseUsageDescription key to your Runner/Info.plist with a string explaining why the app needs location access:

    <key>NSLocationWhenInUseUsageDescription</key>
    <string>[Your explanation here]</string>
  7. Manage Map Styles and Layers

    main

    You can set the initial style via MapWidget.styleUri or change it at runtime using MapboxMap.loadStyleURI or MapboxMap.loadStyleJson.

    To manipulate layers and sources, use the MapboxMap.style object. For example, you can add a GeoJsonSource and then add a LineLayer that references that source.

    // Load a style at runtime
    mapboxMap.loadStyleURI(Styles.LIGHT);
    
    // Add a source and a layer
    var data = await rootBundle.loadString('assets/polyline.geojson');
    await mapboxMap.style.addSource(GeoJsonSource(id: "line", data: data));
    await mapboxMap.style.addLayer(LineLayer(
        id: "line_layer",
        sourceId: "line",
        lineJoin: LineJoin.ROUND,
        lineCap: LineCap.ROUND,
        lineOpacity: 0.7,
        lineColor: Colors.red.value,
        lineWidth: 8.0));
  8. Configure Mapbox Secret Token for iOS and Android

    main

    To download Mapbox binary dependencies, you must provide a Mapbox secret token (sk.*). The configuration method depends on your target platform:

    iOS

    Add your secret token to the ~/.netrc file. If the file does not exist, create it.

    Android

    Set the SDK_REGISTRY_TOKEN environment variable, or add it to your gradle.properties file.

    # ~/.netrc
    machine api.mapbox.com
      login mapbox
      password <your-secret-token>
    # gradle.properties
    SDK_REGISTRY_TOKEN=<your-secret-token>
  9. Handle user map interactions and gestures

    main

    The SDK allows you to manage and observe user gestures on the map:

    • Configure Gestures: Retrieve or update gesture settings via MapboxMap.gestures.
    • Observe Events: Use listeners on the MapWidget to respond to user input:
      • onTapListener
      • onLongTapListener
      • onScrollListener
  10. Animate camera movements with flyTo and easeTo

    main

    To transition the camera smoothly between different states (center, bearing, pitch, zoom, padding, and anchor), use flyTo or easeTo.

    flyTo requires CameraOptions for the target state and MapAnimationOptions to control the timing, such as duration and startDelay.

    mapboxMap?.flyTo(
      CameraOptions(
          anchor: ScreenCoordinate(x: 0, y: 0),
          zoom: 17,
          bearing: 180,
          pitch: 30),
      MapAnimationOptions(duration: 2000, startDelay: 0));
  11. Set up a development environment for Mapbox Maps Flutter

    main

    Follow these steps to prepare the repository for development:

    1. Clone the repository:
      git clone git@github.com:mapbox/mapbox-maps-flutter.git
      cd mapbox-maps-flutter
    2. Reset workspace resolution: Create a pubspec_overrides.yaml file in the package root to reset workspace resolution:
      resolution:
    3. Fetch dependencies:
      flutter pub get
    4. Verify environment:
      flutter analyze
    # pubspec_overrides.yaml
    resolution: