Android Studio选自动补全地点后绘制路径崩溃问题排查
解决Google Maps LatLngBounds.build()抛出"no included points"崩溃问题
从你提供的崩溃日志和代码来看,问题非常明确:调用LatLngBounds.Builder.build()时抛出了IllegalStateException: no included points,这意味着你用来构建地图边界的polyLineList是空的——没有任何坐标点被添加到Builder里,自然无法生成有效的边界对象。
为什么会出现这个问题?
你的代码逻辑里存在几个潜在的漏洞:
- 未检查Directions API返回数据的有效性:如果Google Directions API返回的
routes数组为空,或者某个路线对象里没有overview_polyline字段,polyLineList就会保持为空。 - 未验证Polyline解析结果:如果
decodePoly()方法解析失败(比如points字符串格式错误),也会导致polyLineList为空。 - 缺少空值防护:在遍历
polyLineList构建LatLngBounds之前,你没有检查列表是否为空,直接执行builder.include(latLng),最终Builder里没有任何点,调用build()就会崩溃。
修复方案
我们一步步补上这些漏洞:
1. 给LatLngBounds构建逻辑加上空值检查
在遍历polyLineList之前,先判断列表是否为空,如果为空就直接终止流程并提示用户:
// 在构建LatLngBounds之前添加这段检查 if (polyLineList == null || polyLineList.isEmpty()) { Toast.makeText(WelcomeDriver.this, "无法获取有效路线,请重试", Toast.LENGTH_SHORT).show(); return; } // 原有的边界构建逻辑 LatLngBounds.Builder builder = new LatLngBounds.Builder(); for (LatLng latLng : polyLineList) builder.include(latLng); LatLngBounds bounds = builder.build();
2. 完善Directions API响应的解析逻辑
在解析JSON数据时,增加多层有效性检查,避免无效数据导致空列表:
JSONArray jsonArray = jsonObject.getJSONArray("routes"); // 先检查是否有可用路线 if (jsonArray.length() == 0) { Toast.makeText(WelcomeDriver.this, "未找到前往目的地的路线", Toast.LENGTH_SHORT).show(); return; } for (int i = 0; i < jsonArray.length(); i++) { JSONObject route = jsonArray.getJSONObject(i); // 检查overview_polyline字段是否存在 if (!route.has("overview_polyline")) { continue; } JSONObject poly = route.getJSONObject("overview_polyline"); // 检查points字段是否存在且不为空 if (!poly.has("points") || poly.getString("points").trim().isEmpty()) { continue; } String polyline = poly.getString("points"); polyLineList = decodePoly(polyline); // 解析后立即检查是否成功获取坐标点,成功就取这条路线跳出循环 if (polyLineList != null && !polyLineList.isEmpty()) { break; } }
3. 确保decodePoly方法的正确性
如果你的decodePoly()方法存在问题,会导致解析后的坐标列表为空。这里给你一个经过验证的标准实现,替换你当前的方法:
private List<LatLng> decodePoly(String encoded) { List<LatLng> poly = new ArrayList<>(); int index = 0, len = encoded.length(); int lat = 0, lng = 0; while (index < len) { int b, shift = 0, result = 0; do { b = encoded.charAt(index++) - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20); int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); lat += dlat; shift = 0; result = 0; do { b = encoded.charAt(index++) - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20); int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); lng += dlng; LatLng p = new LatLng((double) lat / 1E5, (double) lng / 1E5); poly.add(p); } return poly; }
把这些修改整合到你的代码里,就能避免因为空坐标列表导致的崩溃,同时也能更好地处理API返回的异常情况。
内容的提问来源于stack exchange,提问作者Saouti Mohamed
相关产品推荐
相关产品推荐

