我正在玩Google Maps for Flutter。我希望地图视图适合屏幕上的所有标记。基本上,我想与Android的here一样。
我假设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)
);
}
在颤振中实现此基本功能的预期方式是什么?有什么建议吗?
答案 0 :(得分:2)
使用此代码执行您想要的操作。
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
setState(() {
controller.animateCamera(CameraUpdate.newLatLngBounds(_bounds(markers), 50));
});
}
答案 1 :(得分:0)
尝试使用控制器将摄像机移至新边界,例如(从plugin example):
mapController.moveCamera(
CameraUpdate.newLatLngBounds(
LatLngBounds(
southwest: const LatLng(-38.483935, 113.248673),
northeast: const LatLng(-8.982446, 153.823821),
),
10.0,
),
);