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

Flutter Google Map两点路线绘制报错(RangeError),求修复方案

解决flutter_polyline_points获取路线时的RangeError问题

这个错误我之前帮开发者排查过好几次,本质是你尝试访问一个空列表的索引0——也就是说polylinePoints.getRouteBetweenCoordinates返回的results是空的,之后你可能直接用了results[0]这类代码,才触发了这个范围错误。咱们一步步来定位和解决:

一、先搞清楚为什么返回空列表

空结果通常是以下几个原因导致的:

  • Google Cloud API密钥没有启用Directions API(flutter_polyline_points底层依赖这个API)
  • API密钥的应用限制配置错误(比如Android包名、iOS Bundle ID填错,导致请求被拒绝)
  • 两点之间没有可导航的路线(比如跨无人区、海洋)
  • 网络问题或者请求超时

二、分步解决方案

1. 验证API密钥的有效性

先直接用浏览器测试Directions API的请求,看看能不能拿到数据:

https://maps.googleapis.com/maps/api/directions/json?origin=38.00000000,40.222222&destination=41.1111111,45.222222222&key=你的API_KEY

如果返回的status字段是"REQUEST_DENIED",那先去Google Cloud控制台:

  • 启用Directions API
  • 检查密钥的应用限制是否和你的Flutter应用匹配(如果暂时不确定,可以先取消限制测试,没问题再加上)

2. 必须处理空结果的情况

就算API正常,也可能出现无路线的情况,所以一定要先判断results是否为空,再进行后续操作:

List<PointLatLng> results = await polylinePoints.getRouteBetweenCoordinates(
  api_key, 
  38.00000000, 
  40.222222, 
  41.1111111, 
  45.222222222
);

// 先判断结果非空再处理
if (results.isNotEmpty) {
  // 生成Polyline并添加到地图
  final Polyline routePolyline = Polyline(
    polylineId: const PolylineId("navigation_route"),
    points: results,
    color: Colors.blueAccent,
    width: 6,
  );
  // 假设你有一个Polylines集合用来管理地图上的路线
  setState(() {
    _polylines.add(routePolyline);
  });
} else {
  // 给用户提示无路线
  ScaffoldMessenger.of(context).showSnackBar(
    const SnackBar(content: Text("无法找到两点间的可导航路线")),
  );
}

3. 用try-catch捕获异常

网络错误、API超时等情况也会导致请求失败,用try-catch包裹可以更清晰地排查问题:

try {
  List<PointLatLng> results = await polylinePoints.getRouteBetweenCoordinates(
    api_key, 
    38.00000000, 
    40.222222, 
    41.1111111, 
    45.222222222
  );
  if (results.isNotEmpty) {
    // 处理路线逻辑
  } else {
    print("无可用路线数据");
  }
} catch (e) {
  print("获取路线失败:$e");
  ScaffoldMessenger.of(context).showSnackBar(
    SnackBar(content: Text("获取路线失败:$e")),
  );
}

4. 确认坐标格式正确

你的代码里坐标顺序是对的(纬度在前,经度在后,符合getRouteBetweenCoordinates的参数要求:apiKey, startLatitude, startLongitude, endLatitude, endLongitude),不过还是要确认数值在合理范围内:纬度±90,经度±180,你的数值是符合要求的,这一点没问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 12:48:10