简体   繁体   中英

Why is this Google Maps polyline not removing?

I've fixed my issue, my question is why this code leaves segments of old polyline.

Note: polyline is a List of type LatLng

for (int i = 0; i < polyline.size(); ++i)
    {
        polyline.get(i).remove();
        polyline.remove(i);
    }

but if I remove the polyline.remove(i) (removing list elements) it works just as expected. What is going on here? It doesn't make sense to me because the polyline.remove(i); is happening after the actual polyline removal, so I'd expect it not to affect it in any way.

for (int i = 0; i < polyline.size(); ++i)
    {
        polyline.get(i).remove();
    }
    polyline.clear()

You're currently removing every other element .

When you remove element 0, everything else "shifts along" so that there's a new element 0... but you're leaving that alone, and moving on to element 1 (which has the value that element 2 used to have).

Options:

  • Always remove from start, just with a while loop:

     while (polyline.size() > 0) { polyline.get(0).remove(); polyline.remove(0); } 
  • Remove from the end

     for (int i = polyline.size() - 1; i >= 0; i--) { polyline.get(i).remove(); polyline.remove(i); } 
  • Call remove on each line and then clear the collection as you're doing in your second snippet

  • The same, but with an enhanced for loop:

     for (LatLng point : polyline) { point.remove(); } polyline.clear(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM