I am using google_map_flutter
in my flutter project and would like to know how to get the visible region (LatLngBounds) when I zoom the map? I want to use the bounds to filter the loaded item from backend.
I try to save the GoogleMapController to a field in my widget but it becomes null in onCameraMove
callback function.
Shall we calculate the visible region by ourselves with zoom value contained in CameraPosition
? If so, does anyone have the equation to calculate that?
Thank you
GoogleMapController? _googleMapController;
GoogleMap(
markers: ctrl.markers,
mapType: MapType.normal,
initialCameraPosition: ctrl.initialCameraPosition,
zoomGesturesEnabled: true,
onMapCreated: (GoogleMapController controller) async {
_googleMapController = controller;
final LatLngBounds bounds = await controller.getVisibleRegion();
await ctrl.listForMap(bounds);
},
onCameraMove: (CameraPosition position) async {
if (_googleMapController != null) { // <------always null
print(await _googleMapController!.getVisibleRegion());
}
print(position); // <---only contains zoom value
},
)
Finally, I get it working and the answer is actually right in the readme of google_map_flutter.
In GetControler (I am using GetX), I have
final Completer<GoogleMapController> googleMapController = Completer();
Then in the view, I have
GoogleMap(
markers: ctrl.markers,
mapType: MapType.normal,
minMaxZoomPreference: const MinMaxZoomPreference(0, 20),
initialCameraPosition: ctrl.initialCameraPosition,
zoomGesturesEnabled: true,
onMapCreated: (GoogleMapController controller) async {
ctrl.googleMapController.complete(controller);
final LatLngBounds bounds = await controller.getVisibleRegion();
print(
'north east: ${bounds.northeast.latitude}, ${bounds.northeast.longitude}');
print(
'north east: ${bounds.southwest.latitude}, ${bounds.southwest.longitude}');
await ctrl.listForMap(bounds);
},
onCameraMove: (CameraPosition position) async {
GoogleMapController googleMapController =
await ctrl.googleMapController.future;
print("onCameraMove");
LatLngBounds bounds = await googleMapController.getVisibleRegion();
print("========================================");
print(bounds.northeast);
print(bounds.southwest);
},
onCameraIdle: () async {
GoogleMapController googleMapController =
await ctrl.googleMapController.future;
print("onCameraIdle");
LatLngBounds bounds = await googleMapController.getVisibleRegion();
print("++++++++++++++++++++++++++++++++++++++++++++++");
print(bounds.northeast);
print(bounds.southwest);
}),
When I zoom the map, onCameraMove
would be called multiple time with the changing bounds and onCameraIdle
is called once at the end of the zoom action.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With