Flutter中PlacePicker搭配Google Maps如何将当前位置设为initialPosition
实现步骤
- 新增状态变量存储当前位置和加载状态
你需要在_SosScreenState类中新增两个状态变量,替换原来固定的静态初始位置:
LatLng? _currentPosition; bool _isLoading = true;
- 调整定位获取逻辑,增加权限判断
修改你现有的getCurrentLocation方法,优先检查定位权限,拿到位置后直接存储为LatLng格式并更新状态:
void getCurrentLocation() async { // 定位权限校验 LocationPermission permission = await Geolocator.checkPermission(); if (permission == LocationPermission.denied) { permission = await Geolocator.requestPermission(); if (permission == LocationPermission.denied) { setState(() => _isLoading = false); return; } } if (permission == LocationPermission.deniedForever) { setState(() => _isLoading = false); return; } // 获取当前定位 final position = await Geolocator.getCurrentPosition( desiredAccuracy: LocationAccuracy.high); setState(() { _currentPosition = LatLng(position.latitude, position.longitude); _isLoading = false; }); }
- 页面初始化时触发定位
重写initState生命周期方法,页面加载时就调用定位接口:
@override void initState() { super.initState(); getCurrentLocation(); }
- 动态渲染PlacePicker
修改_mapAlert方法,定位未完成时显示加载占位,定位完成后将拿到的当前位置传给initialPosition参数:
Widget _mapAlert(BuildContext context) { if (_isLoading) { return const Center(child: CircularProgressIndicator(color: Colors.orange)); } return Center( child: Container( height: 500, width: 500, decoration: BoxDecoration( color: Colors.white, border: Border.all(color: Colors.orangeAccent, width: 2), borderRadius: const BorderRadius.all(Radius.circular(5)), boxShadow: [ BoxShadow( color: Colors.grey.withOpacity(0.5), spreadRadius: 5, blurRadius: 7, offset: const Offset(0, 3), ), ], ), child: PlacePicker( apiKey: '', // 请填入自己的谷歌地图API密钥 initialPosition: _currentPosition ?? SosScreen.kInitialPosition, useCurrentLocation: true, selectInitialPosition: true, usePlaceDetailSearch: true, onPlacePicked: (result) { selectedPlace = result; Navigator.of(context).pop(); setState(() {}); }, forceSearchOnZoomChanged: true, pinBuilder: (context, state) { if (state == PinState.Idle) { return const Icon(Icons.favorite, color: Colors.orange); } else { return const Icon( Icons.favorite_border, color: Colors.orange, ); } }, ) ) ); }
补充说明
如果不需要加载占位,也可以先渲染默认位置,等拿到当前位置后调用PlacePicker的相机移动方法跳转到用户位置,上述实现方案逻辑更简单,能满足打开页面直接展示用户位置的需求。
内容的提问来源于stack exchange,提问作者azeter09
相关产品推荐
相关产品推荐

