0

I try to build to app, that it show a route with polylines, I need to add and remove polylines with conditionals, from a String that is equal to inicioR for show, and finR for remove

Below code fragment of my activity.java. I try to do it like

@Override
public void onDirectionFinderSuccess(List<Route> routes) {
    progressDialog.dismiss();
    polylinePaths = new ArrayList<>();
    originMarkers = new ArrayList<>();
    waypoints = new ArrayList<>();
    destinationMarkers = new ArrayList<>();

    for (Route route : routes) {
        //mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(route.startLocation, 16));
        ((TextView) findViewById(R.id.tvDuration)).setText(route.duration + " Min");
        ((TextView) findViewById(R.id.tvDistance)).setText(route.distance + " Kms");


        PolylineOptions polylineOptions = new PolylineOptions().
                geodesic(true).
                color(Color.BLUE).
                width(10);

        for (int i = 0; i < route.points.size(); i++)
            polylineOptions.add(route.points.get(i));



        if (estado == "inicioR") {
            polylinePaths.add(mMap.addPolyline(polylineOptions));
        }else if (estado == "finR"){
            polylinePaths.remove(mMap.addPolyline(polylineOptions));
        }

    }
}
Paul Chu
  • 1,249
  • 3
  • 19
  • 27
Camilo
  • 1
  • 4

2 Answers2

0

I haven't run this, but it should work

if (estado == "inicioR") {
    polylinePaths.add(mMap.addPolyline(polylineOptions));
}else if (estado == "finR"){
    if (polylinePaths != null && !polylinePaths.isEmpty()) {
        polylinePaths.get(polylinePaths.size()-1).remove(); // remove the lastest line you added. 
        polylinePaths.remove(polylinePaths.size()-1); // remove the lastest line record from ArrayList.
    }
}
Paul Chu
  • 1,249
  • 3
  • 19
  • 27
0

To remove the Polyline, you can use the Polyline.remove() method.

In your case, you need to do the correct check for String equality with String.equals() method. Using == is logically incorrect because it will test for reference of the String. Read more at How do I compare strings in Java?

Hence, your code should be something like this:

if (estado.equals("inicioR")) {
   ..
} else if (estado.equals("finR")){
   ...
}

After that, to remove the Polyline you need to remove the polyline object first then remove the polyline from the list.

if (estado.equals("inicioR")) {
   polylinePaths.add(mMap.addPolyline(polylineOptions));
} else if (estado.equals("finR")){
   // Get the polyline that you want to remove from the list
   // by the index. Here for the example the index is 1
   int index = 1;
   Polyline polyline = polylinePaths.get(index);
   // you need to check for IndexOutOfBoundsException.
   // In this example code, assume that IndexOutOfBoundsException never happened.

  // remove the polyline from the map.
  polyline.remove();
  // then remove from the list.
  polylinePaths.remove(index);
}
ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96