当我使用CameraUpdate.newLatLngBounds
. 它在设置边界后立即重新定位到北太平洋,不确定是什么原因造成的,但这里有一个解决方法 -
LatLngBounds
您可以计算要设置的边界的中心,而不是使用 设置地图位置
// the bounds you want to set
LatLngBounds bounds = LatLngBounds(
southwest: LatLng(23.785182, 90.330702),
northeast: LatLng(24.582782, 88.821163),
);
// calculating centre of the bounds
LatLng centerBounds = LatLng(
(bounds.northeast.latitude + bounds.southwest.latitude)/2,
(bounds.northeast.longitude + bounds.southwest.longitude)/2
);
// setting map position to centre to start with
controller.moveCamera(CameraUpdate.newCameraPosition(CameraPosition(
target: centerBounds,
zoom: 17,
)));
zoomToFit(controller, bounds, centerBounds);
将地图位置设置为边界的中心(并放大)后,您需要继续缩小直到可见地图区域覆盖您要设置的边界。您可以使用 获取可见的地图区域controller.getVisibleRegion()
。这是实现 -
Future<void> zoomToFit(GoogleMapController controller, LatLngBounds bounds, LatLng centerBounds) async {
bool keepZoomingOut = true;
while(keepZoomingOut) {
final LatLngBounds screenBounds = await controller.getVisibleRegion();
if(fits(bounds, screenBounds)){
keepZoomingOut = false;
final double zoomLevel = await controller.getZoomLevel() - 0.5;
controller.moveCamera(CameraUpdate.newCameraPosition(CameraPosition(
target: centerBounds,
zoom: zoomLevel,
)));
break;
}
else {
// Zooming out by 0.1 zoom level per iteration
final double zoomLevel = await controller.getZoomLevel() - 0.1;
controller.moveCamera(CameraUpdate.newCameraPosition(CameraPosition(
target: centerBounds,
zoom: zoomLevel,
)));
}
}
}
bool fits(LatLngBounds fitBounds, LatLngBounds screenBounds) {
final bool northEastLatitudeCheck = screenBounds.northeast.latitude >= fitBounds.northeast.latitude;
final bool northEastLongitudeCheck = screenBounds.northeast.longitude >= fitBounds.northeast.longitude;
final bool southWestLatitudeCheck = screenBounds.southwest.latitude <= fitBounds.southwest.latitude;
final bool southWestLongitudeCheck = screenBounds.southwest.longitude <= fitBounds.southwest.longitude;
return northEastLatitudeCheck && northEastLongitudeCheck && southWestLatitudeCheck && southWestLongitudeCheck;
}