我无法删除折线

I can't remove Polyline

我构建了一个应用程序来用另一个点追踪我的当前位置,当我的当前位置更新时,创建一条新的折线,但最后的 折线 没有删除。

我尝试使用 polyline.remove(); 但没有用。

这是我使用的代码片段:

 protected void onPostExecute(List<List<HashMap<String, String>>> result) {
            ArrayList<LatLng> points = null;
            PolylineOptions lineOptions = null;
            MarkerOptions markerOptions = new MarkerOptions();
            String distance = "";
            String duration = "";

            if (result.size() < 1) {
                Toast.makeText(getBaseContext(), "No Points", Toast.LENGTH_SHORT).show();
                return;
            }

            // Traversing through all the routes
            for (int i = 0; i < result.size(); i++) {
                points = new ArrayList<LatLng>();
                lineOptions = new PolylineOptions();

                // Fetching i-th route
                List<HashMap<String, String>> path = result.get(i);

                // Fetching all the points in i-th route
                for (int j = 0; j < path.size(); j++) {
                    HashMap<String, String> point = path.get(j);

                    if (j == 0) {    // Get distance from the list
                        distance = (String) point.get("distance");
                        continue;
                    } else if (j == 1) { // Get duration from the list
                        duration = (String) point.get("duration");
                        continue;
                    }

                    double lat = Double.parseDouble(point.get("lat"));
                    double lng = Double.parseDouble(point.get("lng"));
                    LatLng position = new LatLng(lat, lng);

                    points.add(position);
                }

                // Adding all the points in the route to LineOptions
                lineOptions.addAll(points);
                lineOptions.width(4);
                lineOptions.color(Color.BLUE);

            }

            tvDistanceDuration.setText("Distance:" + distance + ", Duration:" + duration);

             polyline = mMap.addPolyline(lineOptions);

        }

您需要使用列表来跟踪折线。然后如果你想删除折线,你可以从列表中删除它。像这样:

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

// When adding the polyline add to the list
polylines.add(mMap.addPolyline(lineOptions));

// To remove all the polyline
for(Polyline polyline: polylines) {
  polyline.remove();
}

// then clear the list
polylines.clear();