constrain method

  1. @override
MapCamera? constrain(
  1. MapCamera camera
)
override

Create a new constrained camera based off the current camera

May return null if no appropriate camera could be generated by movement, for example because the camera was zoomed too far out.

Implementation

@override
MapCamera? constrain(MapCamera camera) {
  final testZoom = camera.zoom;
  final testCenter = camera.center;

  final nePixel = camera.project(bounds.northEast, testZoom);
  final swPixel = camera.project(bounds.southWest, testZoom);

  final halfSize = camera.size / 2;

  // Find the limits for the map center which would keep the camera within the
  // [latLngBounds].
  final leftOkCenter = math.min(swPixel.x, nePixel.x) + halfSize.x;
  final rightOkCenter = math.max(swPixel.x, nePixel.x) - halfSize.x;
  final topOkCenter = math.min(swPixel.y, nePixel.y) + halfSize.y;
  final botOkCenter = math.max(swPixel.y, nePixel.y) - halfSize.y;

  // Stop if we are zoomed out so far that the camera cannot be translated to
  // stay within [latLngBounds].
  if (leftOkCenter > rightOkCenter || topOkCenter > botOkCenter) return null;

  final centerPix = camera.project(testCenter, testZoom);
  final newCenterPix = Point(
    centerPix.x.clamp(leftOkCenter, rightOkCenter),
    centerPix.y.clamp(topOkCenter, botOkCenter),
  );

  if (newCenterPix == centerPix) return camera;

  return camera.withPosition(
    center: camera.unproject(newCenterPix, testZoom),
  );
}