我正在尝试使用Google Maps for Flutter进行实验。我希望地图视图适应屏幕上的所有标记。基本上,我想要做与这里在安卓中所做的相同的事情。
我假设cameraTargetBounds
描述了应该适合屏幕边界内的区域。但实际上,它并没有完全适配该区域,而是聚焦于中间某处。
到目前为止,我已经做了什么:
@override
Widget build(BuildContext context) {
final bloc = Provider.of<BlocMap>(context);
return SafeArea(
child: Container(
child: Stack(
children: <Widget>[
Positioned.fill(
child: StreamBuilder<MapData>(
stream: bloc.mapData,
builder: (context, snap) {
final mapData = snap.data;
print("mapData: $mapData");
return GoogleMap(
padding: EdgeInsets.only(bottom: 42),
mapType: _mapType,
cameraTargetBounds: mapData?.markers == null
? CameraTargetBounds.unbounded
: CameraTargetBounds(_bounds(mapData?.markers)),
initialCameraPosition: _cameraPosition,
myLocationEnabled: true,
myLocationButtonEnabled: true,
gestureRecognizers: _buildGestureRecognizer(),
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
markers: mapData?.markers,
polylines: mapData?.polylines,
polygons: mapData?.polygons,
onLongPress: (latLng) {
print("LatLng: $latLng");
},
);
}),
),
Positioned(
left: 0,
right: 0,
bottom: 0,
child: _buildBtnBar(),
)
],
),
),
);
LatLngBounds _bounds(Set<Marker> markers) {
if (markers == null || markers.isEmpty) return null;
return _createBounds(markers.map((m) => m.position).toList());
}
LatLngBounds _createBounds(List<LatLng> positions) {
final southwestLat = positions.map((p) => p.latitude).reduce((value, element) => value < element ? value : element); // smallest
final southwestLon = positions.map((p) => p.longitude).reduce((value, element) => value < element ? value : element);
final northeastLat = positions.map((p) => p.latitude).reduce((value, element) => value > element ? value : element); // biggest
final northeastLon = positions.map((p) => p.longitude).reduce((value, element) => value > element ? value : element);
return LatLngBounds(
southwest: LatLng(southwestLat, southwestLon),
northeast: LatLng(northeastLat, northeastLon)
);
}
在Flutter中,实现这种基本功能的预期方法是什么?有什么建议吗?