删除 Google 地图上的先前路线

Remove previous direction route on Google Maps

我正在使用 jd-alexander library 在 google 地图上显示方向路线,我的问题是,当我请求另一条方向路线时,会创建新路线,但不会删除之前创建的路线。我想删除以前的路线,然后显示新路线。

@Override
public void onRoutingSuccess(ArrayList<Route> routeArrayList, int i) {

    //code to add route to map here.
     polylines = new ArrayList<>();
     if (polylines.size() > 0) {
         erasePolylines();
     }
         polylines = new ArrayList<>();
         //add route(s) to the map.
     polylines.clear();
         for (i = 0; i < routeArrayList.size(); i++) {

             //In case of more than 5 alternative routes
             int colorIndex = i % COLORS.length;

             PolylineOptions polyOptions = new PolylineOptions();
             polyOptions.color(getResources().getColor(COLORS[colorIndex]));
             polyOptions.width(10 + i * 3);
             polyOptions.addAll(routeArrayList.get(i).getPoints());
             Polyline polyline = mMap.addPolyline(polyOptions);
             polylines.add(polyline);

             Toast.makeText(getApplicationContext(), "Route " + (i + 1) + ": distance - " + routeArrayList.get(i).
                     getDistanceValue() + ": duration - " + routeArrayList.get(i).getDurationValue(), Toast.LENGTH_SHORT).show();
         }
 }

private void erasePolylines(){
    for(Polyline line : polylines){
        line.remove();
    }
    polylines.clear();
}

我该如何解决这个问题?

polylines = new ArrayList<>();
 if (polylines.size() > 0) {
     for (Polyline poly : polylines) {
         poly.remove();
     }
     erasePolylines();
 }
     polylines = new ArrayList<>();
     //add route(s) to the map.
 polylines.clear();
     for (i = 0; i < routeArrayList.size(); i++) {

         //In case of more than 5 alternative routes
         int colorIndex = i % COLORS.length;

         PolylineOptions polyOptions = new PolylineOptions();
         polyOptions.color(getResources().getColor(COLORS[colorIndex]));
         polyOptions.width(10 + i * 3);
         polyOptions.addAll(routeArrayList.get(i).getPoints());
         Polyline polyline = mMap.addPolyline(polyOptions);
         polylines.add(polyline);

         Toast.makeText(getApplicationContext(), "Route " + (i + 1) + ": distance - " + routeArrayList.get(i).
                 getDistanceValue() + ": duration - " + routeArrayList.get(i).getDurationValue(), Toast.LENGTH_SHORT).show();
     }
 }

你的代码没问题,除了这里:

//You're initializing your list "POLILYNES" and trying remove empty list, Remove the 
//lines I commented.

@Override
public void onRoutingSuccess(ArrayList<Route> routeArrayList, int i) {

//code to add route to map here.
 polylines = new ArrayList<>(); // DELETE THIS LINE
 if (polylines.size() > 0) {
     erasePolylines();
 }
     polylines = new ArrayList<>(); // DELETE THIS LINE
     //add route(s) to the map.
 polylines.clear();

    ...
 }