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

Google Map多色折线绘制问题求助:polyline.setPoints报错

问题分析与解决方案

核心问题1:polyline.getPoints()返回不可变列表

Google Maps Android SDK中,Polyline.getPoints()返回的是不可修改的List,直接调用points.add()会抛出UnsupportedOperationException,这是代码报错的直接原因。

核心问题2:颜色切换时的逻辑漏洞

当相邻点颜色不同时,原代码未完成新颜色线段的初始化(未设置颜色、端点样式等属性,也未将新线段添加到地图),导致后续同色点无法正确续接。

修复后的代码

PolylineOptions options = new PolylineOptions();
Polyline polyline = null;

for (int i = 1; i < coloredPointArrayLit.size(); i++) {
    ColoredPoint current = coloredPointArrayLit.get(i);
    ColoredPoint prev = coloredPointArrayLit.get(i - 1);

    if (current.color == prev.color) {
        if (polyline != null) {
            // 复制原有不可变列表为可变列表
            List<LatLng> points = new ArrayList<>(polyline.getPoints());
            points.add(current.coordinates);
            polyline.setPoints(points);
        } else {
            // 初始化新的同色线段
            options.add(prev.coordinates)
                  .add(current.coordinates)
                  .color(current.color)
                  .jointType(JointType.ROUND)
                  .endCap(roundCap)
                  .startCap(roundCap)
                  .width(DensityTool.adjustToDensity(context, 7));
            polyline = this.googleMap.addPolyline(options);
            // 重置options,避免后续复用污染
            options = new PolylineOptions();
        }
    } else {
        // 颜色切换,直接初始化并添加新线段
        options.add(prev.coordinates)
              .add(current.coordinates)
              .color(current.color)
              .jointType(JointType.ROUND)
              .endCap(roundCap)
              .startCap(roundCap)
              .width(DensityTool.adjustToDensity(context, 7));
        polyline = this.googleMap.addPolyline(options);
        options = new PolylineOptions();
    }
}

关键修复点

  • 将List<LatLng> points = polyline.getPoints();替换为List<LatLng> points = new ArrayList<>(polyline.getPoints());,把不可变列表转为可变列表后再添加新点。
  • 颜色切换时直接完成新线段的属性设置并添加到地图,避免逻辑混乱。
  • 每次初始化线段后重置options,防止不同线段的属性互相干扰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 05:01:01