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

Flutter中getLocation()静态访问错误及Polyline不显示问题

问题解决方案

1. 解决getLocation()静态访问错误

错误原因:getLocation()是Location类的实例方法,直接用类名Location调用属于静态访问实例方法,因此触发报错。

修复步骤:

  • 使用创建的location实例调用getLocation(),而非类名。
  • 补充位置权限请求逻辑,否则无法获取位置数据,页面会一直显示"Loading"。

修改后的getCurrentLocation()方法:

void getCurrentLocation() async {
  Location location = Location();

  // 先检查并请求位置服务权限
  bool serviceEnabled;
  PermissionStatus permissionGranted;

  serviceEnabled = await location.serviceEnabled();
  if (!serviceEnabled) {
    serviceEnabled = await location.requestService();
    if (!serviceEnabled) {
      return;
    }
  }

  permissionGranted = await location.hasPermission();
  if (permissionGranted == PermissionStatus.denied) {
    permissionGranted = await location.requestPermission();
    if (permissionGranted != PermissionStatus.granted) {
      return;
    }
  }

  // 获取当前位置并更新状态
  location.getLocation().then(
    (locationData) {
      setState(() {
        currentLocation = locationData;
      });
    },
  );
}

2. 解决Polyline无法显示的问题

以下是常见原因及对应修复方案:

原因1:Google API Key未启用Directions API

flutter_polyline_points依赖Google Directions API获取路线坐标,需在Google Cloud控制台启用该API,并确保API Key绑定了正确的项目。

原因2:地图初始视角未覆盖路线区域

当前地图初始相机位置为用户当前位置,若路线不在视野范围内,会导致Polyline不可见。可调整初始相机位置至包含起点和终点的区域:

// 替换原initialCameraPosition代码
initialCameraPosition: CameraPosition(
  target: LatLng(
    (sourcelocation.latitude + destination.latitude) / 2,
    (sourcelocation.longitude + destination.longitude) / 2,
  ),
  zoom: 14.5,
),

原因3:Polyline数据未正确填充或更新

  • 添加日志验证路线点是否成功获取:
void getPolyPoints() async {
  PolylinePoints polylinePoints = PolylinePoints();

  PolylineResult result = await polylinePoints.getRouteBetweenCoordinates(
    googleApiKey,
    PointLatLng(sourcelocation.latitude, sourcelocation.longitude),
    PointLatLng(destination.latitude, destination.longitude),
  );
  
  // 打印结果验证是否获取到路线点
  print("路线点数量:${result.points.length}");
  print("API返回状态:${result.status}");

  if (result.points.isNotEmpty) {
    polylineCoordinates.clear(); // 清空旧数据避免重复
    result.points.forEach(
      (PointLatLng point) => polylineCoordinates.add(
        LatLng(point.latitude, point.longitude),
      ),
    );
    setState(() {});
  }
}
  • 确保googleApiKey替换为自身的有效密钥,且密钥未被限制使用范围。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 20:16:10