Flutter中google_maps_flutter获取定位按钮点击及实时定位坐标
解决方案
需求1:点击定位按钮时打印当前LatLng
google_maps_flutter没有直接提供定位按钮的点击回调,但点击该按钮会触发设备位置的重新获取,我们可以利用组件自带的onMyLocationChange回调捕获这个事件,同时满足需求2。
需求2:定位标记移动时实时打印变更后的LatLng
onMyLocationChange回调会在设备位置更新(包括定位标记移动)时实时触发,直接在这个回调里打印位置即可。
修改后的完整代码如下:
final Completer<GoogleMapController> _controller = Completer<GoogleMapController>(); static const CameraPosition _kGooglePlex = CameraPosition( target: LatLng(37.42796133580664, -122.085749655962), zoom: 14.4746, ); GoogleMap( onTap: (argument) { print("hello $argument"); }, zoomControlsEnabled: false, myLocationButtonEnabled: true, myLocationEnabled: true, initialCameraPosition: _kGooglePlex, onMapCreated: (GoogleMapController controller) { _controller.complete(controller); }, onCameraMove: (position) { print("hello ${position.bearing}"); }, // 添加以下回调处理两个需求 onMyLocationChange: (location) { // 点击定位按钮或位置更新时触发 final currentLatLng = LatLng(location.latitude, location.longitude); print("当前定位位置: $currentLatLng"); }, ),
说明
onMyLocationChange是google_maps_flutter自带的回调,无需第三方包,当设备位置更新(包括点击定位按钮主动获取位置)时会被调用。- 每次定位标记移动(设备位置变化),该回调都会实时触发,打印最新的LatLng。
- 点击定位按钮后,组件会重新获取当前位置并触发该回调,从而打印当前定位的LatLng。
内容的提问来源于stack exchange,提问作者Vivek Raj Singh
相关产品推荐
相关产品推荐

