Romes
Romes

Reputation: 3118

Google Maps API v3 remove all polylines

Little background. I have a navigation setup for when you click on a certain navigation item, it creates markers on the map. If you click on a different navigation item, it removes the previous markers and sets up new ones.

Well now I am working with polylines and trying to create the same concept here with the polylines, however I am having a difficult time. Here is what I have:

    // Global variable for array of lines
    var points= [];

Setup my points.

    line1 = new google.maps.LatLng(line1Start, line1Finish);
    line2 = new google.maps.LatLng(line2Start, line2Finish);
    line3 = new google.maps.LatLng(line3Start,line3Finish);

    points.push(line1, line2, line3);

Setup my polylines.

    var polyline = new google.maps.Polyline({
       path:points,
       strokeColor:"#FF0000",
       strokeOpacity:1.0,
       strokeWeight:2
    });

Initialize the map with lines.

    polyline.setMap(map);

All works well. The lines are created and show up between my markers. Now lets remove them (or not...)

    function removeLines() {
      if (points) {
           points.length = 0;
      }
      points = [];
    }

removeLines() is being called at the beginning of the function to clear them, then new ones are setup. This indeed clears my points in the points array, however on the map itself the polylines still show up and do not disappear like my markers do.

What gives?!

Upvotes: 25

Views: 53227

Answers (2)

Aravind Asok
Aravind Asok

Reputation: 514

polyline is just an array of LatLng objects, not individual Polylines. I think you probably need a separate array for the polylines, which you can then loop over to remove them all. Create a global array line.

 var line = [];
 polyline = new google.maps.Polyline({
        path: points,
        strokeColor: "#FF0000",
        strokeOpacity: 1.0,
        strokeWeight: 2
    });
 line.push(polyline);

Now you are pushing all the polyline objects into an array line. You can make it invisible or remove it from the map by looping it like this:

for (i=0; i<line.length; i++) 
{                           
  line[i].setMap(null); //or line[i].setVisible(false);
}

Upvotes: 22

friism
friism

Reputation: 19279

You have to do polyline.setMap(null), that will remove the line from the map. Documentation.

Upvotes: 46

Related Questions