Search code examples
fluttermapboxmapbox-gl-jsmapbox-glmapbox-android

Current zoom level in Flutter Mapbox_gl


I'm using the mapbox_gl: ~0.16.0 plugin in my Flutter application, and I need to know the current zoom level when the user moves the map (or after move end)! However it always returns the original zoom level rather than the current zoom level. Nevertheless, when I attempt to obtain the current viewport bound, it provides the proper coordinates. I would appreciate any assistance. I'm going with this approach:

/* view code */
MapboxMap(
  onMapCreated: (mController) {
    // Assign the MapboxMapController instance to mapboxMapController
    mapboxMapController = mController;
    controller.onMapCreated(mController);
  },
  zoomGesturesEnabled: true,
  accessToken:"<MAPBOX ACCESS TOKEN>",
  initialCameraPosition: const CameraPosition(
      target: LatLng(47.5973305239398, -107.06058413659325),
      zoom: 15.0),
  doubleClickZoomEnabled: true,
  onCameraIdle: () {
    controller.getView(mapboxMapController);
  },
  styleString: "mapbox://styles/mapbox/outdoors-v12",
)
/* view code */
...
/* controller code */
Future<void> getView(MapboxMapController mapboxMap) async {
    mapboxMap.getVisibleRegion().then(
      (bounds) async {
        double northeastLat = bounds.northeast.latitude;
        double northeastLng = bounds.northeast.longitude;
        double northwestLat = bounds.northeast.latitude;
        double northwestLng = bounds.southwest.longitude;
        double southeastLat = bounds.southwest.latitude;
        double southeastLng = bounds.northeast.longitude;
        double southwestLat = bounds.southwest.latitude;
        double southwestLng = bounds.southwest.longitude;
        double zoomLevel = mapboxMap.cameraPosition!.zoom;
        print(zoomLevel); // this always print 15.0, which is my intial zoom level
      },
    );
  }
/* controller code */

Most of the documents or example code told to use this, but it's not working for me! I've reviewed the Mapbox Maps documentation, but I couldn't find a clear example for achieving this specific functionality. Any assistance or code snippets would be highly appreciated. Thank you!

mapboxMap.getCameraPosition().zoom;

Solution

  • Set the trackCameraPosition property of MapboxMap to true.

    MapboxMap(
      // ...
      trackCameraPosition: true,
    )
    

    See this issue on GitHub: CameraPosition not updating