You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何获取GPS当前位置并加载到GoogleMap?

问题分析与修复方案

你的代码存在两个关键问题导致运行报错:

  1. static const变量非法引用实例变量
    _MyPostn被声明为static const,但它的target属性引用了实例变量_center。static成员属于类本身,无法访问实例级别的变量;同时const变量要求值在编译时确定,而_center是在运行时通过定位接口异步获取后才赋值的,两者逻辑冲突。

  2. 初始状态下_center未完成初始化
    _center用late修饰,在getUserLocation异步方法执行完成前并未赋值,若直接用于地图初始位置,会触发未初始化异常。


修改后的代码示例

late LatLng _center;
late Position currentLocation;
GoogleMapController? _mapController;

// 设置默认初始位置,避免未初始化问题
final LatLng _defaultCenter = const LatLng(39.9042, 116.4074);

@override
void initState() {
  super.initState();
  _center = _defaultCenter; // 先赋值默认位置
  getUserLocation();
}

Future<Position> locateUser() async {
  return Geolocator.getCurrentPosition(
      desiredAccuracy: LocationAccuracy.high);
}

getUserLocation() async {
  currentLocation = await locateUser();
  setState(() {
    _center = LatLng(currentLocation.latitude, currentLocation.longitude);
  });
  // 获取到位置后,动态移动地图到当前位置
  _mapController?.animateCamera(
    CameraUpdate.newCameraPosition(
      CameraPosition(target: _center, zoom: 14.4746),
    ),
  );
  print('center $_center');
}

@override
Widget build(BuildContext context) {
  return GoogleMap(
    initialCameraPosition: CameraPosition(
      target: _center,
      zoom: 14.4746,
    ),
    onMapCreated: (controller) {
      _mapController = controller;
    },
    myLocationEnabled: true, // 开启当前位置蓝点显示
  );
}

额外配置要求

  • Android端需在AndroidManifest.xml中添加定位权限:
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    
  • iOS端需在Info.plist中添加权限描述:
    <key>NSLocationWhenInUseUsageDescription</key>
    <string>需要获取您的位置来显示地图当前位置</string>
    

内容的提问来源于stack exchange,提问作者SaFaL

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 20:37:19