Android google 地图去掉折线

Android google maps getting rid of polyline

我正在构建一个 android 应用程序来获取用户的当前位置并查找附近的景点。当我 select 一个景点时,一条路线从当前位置绘制到它,但是当我第二次这样做时,第一条路线停留在那里,我希望它消失。下面是我用来画线的代码。每次绘制一个方向时都会调用它。每次调用方法之前,我都尝试使用 line.remove 但这会删除两行。有什么建议吗?

for (int i = 0; i < pontos.size() - 1; i++) {
                    LatLng src = pontos.get(i);
                    LatLng dest = pontos.get(i + 1);
                    try{
                        //here is where it will draw the polyline in your map
                        line = mMap.addPolyline(new PolylineOptions()
                                .add(new LatLng(src.latitude, src.longitude),
                                        new LatLng(dest.latitude,                dest.longitude))
                                .width(2).color(Color.RED).geodesic(true));

将你的 Polylines 保存在一个数组中,这样你就可以在添加其他之前删除它们:

List<Polyline> mPolylines = new ArrayList<>();

private void someMethod() {
    // Remove polylines from map
    for (Polyline polyline : mPolylines) {
        polyline.remove();
    }
    // Clear polyline array
    mPolylines.clear();

    for (int i = 0; i < pontos.size() - 1; i++) {
        LatLng src = pontos.get(i);
        LatLng dest = pontos.get(i + 1);

        mPolylines.add(mMap.addPolyline(new PolylineOptions()
                .add(new LatLng(src.latitude, src.longitude),
                        new LatLng(dest.latitude, dest.longitude))
                .width(2).color(Color.RED).geodesic(true)));

    }
}