Google Maps API v3 remove all polylines

Romes picture Romes · Mar 1, 2012 · Viewed 44.2k times · Source

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?!

Answer

friism picture friism · Mar 1, 2012

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