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 double testZoom = camera.zoom;
  final LatLng testCenter = camera.center;

  final Offset aPixel = camera.projectAtZoom(LatLng(a, 0), testZoom);
  final Offset bPixel = camera.projectAtZoom(LatLng(b, 0), testZoom);

  final Size halfSize = camera.size / 2;

  // Find the limits for the map center which would keep the camera within the
  // [north] and [south] bounds.
  final double topOkCenter = math.min(aPixel.dy, bPixel.dy) + halfSize.height;
  final double botOkCenter = math.max(aPixel.dy, bPixel.dy) - halfSize.height;

  // Stop if we are zoomed out so far that the camera cannot be translated to
  // stay within the [north] and [south] bounds.
  if (topOkCenter > botOkCenter) {
    return null;
  }

  final Offset centerPix = camera.projectAtZoom(testCenter, testZoom);
  final newCenterPix = Offset(
    centerPix.dx,
    centerPix.dy.clamp(topOkCenter, botOkCenter),
  );

  if (newCenterPix == centerPix) {
    return camera;
  }

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