Search code examples
flutterdartmapbox-gl

MapboxMap's controller has cameraPosition equal to null when called by a listener


I'm trying to add a marker at the camera position. So I need to get the camera's position whenever the user moves trough the map. After a quick research, I found out that it should be easy to setup a listener that get called each time the user moves, and extract the camera position using controller.cameraPosition. It looked greatly easy, but the controller.cameraPosition is always null when the listener get called. Only when the onMapCreated function is triggered, it has the right values.

Here's a easy reproducable code sample:

import 'package:flutter/material.dart';

import 'package:mapbox_gl/mapbox_gl.dart';

import 'package:test_01/secretAccessToken.dart';

void main() {
  runApp(
    MaterialApp(
      home: MyMapBoxMap(),
    )
  );
}

class MyMapBoxMap extends StatefulWidget {
  @override
  _MyMapBoxMapState createState() => _MyMapBoxMapState();
}

class _MyMapBoxMapState extends State<MyMapBoxMap> {
  MapboxMapController mapController;

  void _onMapCreated(MapboxMapController controller) {
    mapController = controller;
    print("On map created: ${mapController.cameraPosition}");
    mapController.addListener(() {
      print(mapController.cameraPosition);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: MapboxMap(
        onMapCreated: _onMapCreated,
        initialCameraPosition: CameraPosition(target: LatLng(42, 42), zoom: 3),
        accessToken: secretAccessToken,
      ),
    );
  }
}

(The secretAccessToken is a private access token obtainable on the mapbox website)

Here's the output's log:

...
I/flutter (18328): On map created: CameraPosition(bearing: 0.0, target: LatLng(42.0, 42.0), tilt: 0.0, zoom: 3.0)
...
I/flutter (18328): null
...

I am using mapbox_gl: ^0.8.0

Am I missing something pretty obvious that I should've read ?
Thanks for reading


Solution

  • The answer is pretty simple. You can read here (on the doc of mapbox_gl) that cameraPosition

    Will be null, if MapboxMap.trackCameraPosition is false

    Feeling a bit stupid rn