如何为google_maps_flutter设置myLocationButton点击时的缩放重置逻辑
解决方案
官方默认的myLocationButton未暴露点击回调接口,无法直接监听点击事件修改缩放逻辑,因此推荐通过自定义按钮的方式实现需求,该方案可控性更高,也能完美满足重置缩放的要求。
方案1:自定义我的位置按钮实现点击重置缩放
- 第一步:修改GoogleMap配置,关闭默认的我的位置按钮
把原有GoogleMap组件中的myLocationButtonEnabled属性值改为false - 第二步:使用Stack组件嵌套GoogleMap和自定义浮动按钮,完整示例代码如下:
Stack( children: [ // 原有GoogleMap代码 GoogleMap( padding: EdgeInsets.only(bottom: _mapBottomPadding), mapType: MapType.normal, initialCameraPosition: _baseLocation, myLocationButtonEnabled: false, // 禁用默认按钮 myLocationEnabled: true, zoomControlsEnabled: true, zoomGesturesEnabled: true, polylines: _polylineSet, markers: _markersSet, onMapCreated: (GoogleMapController controller) async { if (!_controller.isCompleted) { _controller.complete(controller); } _googleMapController = controller; setCameraPosition( position: locationData.getCurrentAddress.position as Position); setMapBounds(); setState(() {}); }, ), // 自定义我的位置按钮,调整position参数修改按钮位置 Positioned( top: 16, right: 16, child: FloatingActionButton( backgroundColor: Colors.white, mini: true, child: const Icon(Icons.my_location, color: Colors.black87), onPressed: () async { // 获取当前用户定位,需提前申请定位权限 Position currentPosition = await Geolocator.getCurrentPosition( locationSettings: const LocationSettings(accuracy: LocationAccuracy.high) ); // 构建相机位置,指定需要重置的缩放级别(可自行修改zoom的数值) CameraPosition targetCamera = CameraPosition( target: LatLng(currentPosition.latitude, currentPosition.longitude), zoom: 15, ); // 执行相机动画 _googleMapController?.animateCamera(CameraUpdate.newCameraPosition(targetCamera)); }, ), ) ], )
方案2:执行newLatLngBounds相机动画后重置缩放
如果需要在调用setMapBounds()适配边界后直接调整缩放级别,可以在边界适配动画执行完成后,再调用一次缩放设置:
// 先执行边界适配动画 await _googleMapController! .animateCamera(CameraUpdate.newLatLngBounds(latLngBounds, 70)); // 适配完成后,重置为指定的缩放级别 await _googleMapController! .animateCamera(CameraUpdate.zoomTo(14)); // 14可替换为你需要的缩放值
注意:使用Geolocator获取定位前需要提前申请安卓和iOS端的定位权限,否则会出现定位失败的问题。
内容的提问来源于stack exchange,提问作者Barnett Temwa Msiska
相关产品推荐
相关产品推荐

