Search code examples
javaandroidgoogle-mapspolyline

Polylines not being removed from GoogleMap


I have a Map where i'm placing markers and connecting them with PolyLines:

PolylineOptions p = new PolylineOptions();
p.color(Color.BLUE);
p.width((float) 7.0);
Polyline polyLine = this.mMap.addPolyline(p);
p.add(actualLocation);
LatLng previousPoint = latLngs.get(latLngs.size() - 2);
p.add(previousPoint);
this.polyLines.add(polyLine);
mMap.addPolyline(p);

I'm saving the object p in an arraylist:

ArrayList<Polyline> polyLines = new ArrayList<>();

When i remove the last marker i want to remove the last polyline too. I'm doing the next:

if (polyLines.size() > 0) {
     Polyline polyLine = polyLines.get(polyLines.size() - 1);
     polyLine.remove();
     polyLines.remove(polyLines.size() - 1);
}

I'm removing the marker but the polyline keeps in the Map. I'm removing it from the ArrayList too.

Can anyone help me to find out what is happening? I've tried to make the polyline invisible or changing the colour but it won't work.


Solution

  • It looks to me like you are in fact adding two polylines to the map... If PolylineOptions() are mutable once attached to a Polyline, they are in the same spot, otherwise you are adding one without positioning followed by a second. Only the second Polyline is being added to your List.

    Instead of this:

    PolylineOptions p = new PolylineOptions();
    p.color(Color.BLUE);
    p.width((float) 7.0);
    Polyline polyLine = this.mMap.addPolyline(p); // Add before location set
    p.add(actualLocation);
    LatLng previousPoint = latLngs.get(latLngs.size() - 2);
    p.add(previousPoint);
    this.polyLines.add(polyLine);
    mMap.addPolyline(p); // Add after location set
    

    Did you want to do this?

    PolylineOptions p = new PolylineOptions();
    p.color(Color.BLUE);
    p.width((float) 7.0);
    p.add(actualLocation);
    LatLng previousPoint = latLngs.get(latLngs.size() - 2);
    p.add(previousPoint);
    Polyline polyLine = mMap.addPolyline(p);
    this.polyLines.add(polyLine);