user2052514
user2052514

Reputation: 467

Android google maps getting rid of polyline

I am building an android application that gets the users current position and find nearby attractions. When I select an attraction a route is drawn to it from the current position but when I do this a second time the first route stays there, I want it to disappear. Below is the code I use to draw the line. Each time a direction is drawn this is called. I have tried to use line.remove each time before method is called but this removes both lines then. Any suggestions?

for (int i = 0; i < pontos.size() - 1; i++) {
                    LatLng src = pontos.get(i);
                    LatLng dest = pontos.get(i + 1);
                    try{
                        //here is where it will draw the polyline in your map
                        line = mMap.addPolyline(new PolylineOptions()
                                .add(new LatLng(src.latitude, src.longitude),
                                        new LatLng(dest.latitude,                dest.longitude))
                                .width(2).color(Color.RED).geodesic(true));

Upvotes: 1

Views: 401

Answers (1)

Simas
Simas

Reputation: 44118

Save your Polylines in an array so you can remove them before other ones are added:

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

private void someMethod() {
    // Remove polylines from map
    for (Polyline polyline : mPolylines) {
        polyline.remove();
    }
    // Clear polyline array
    mPolylines.clear();

    for (int i = 0; i < pontos.size() - 1; i++) {
        LatLng src = pontos.get(i);
        LatLng dest = pontos.get(i + 1);

        mPolylines.add(mMap.addPolyline(new PolylineOptions()
                .add(new LatLng(src.latitude, src.longitude),
                        new LatLng(dest.latitude, dest.longitude))
                .width(2).color(Color.RED).geodesic(true)));

    }
}

Upvotes: 1

Related Questions