Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Maps API v3 remove all polylines

Tags:

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

like image 791
Romes Avatar asked Mar 01 '12 06:03

Romes


People also ask

How do I remove a polyline from Google Maps?

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

How do I remove all markings from Google Maps?

Find the “Layers” menu in the bottom left corner of the screen. Hover your cursor over the box and wait until more options appear. Click “More” to open the Map Details menu. Under “Map Type,” you'll see a checked box next to “Labels.” Uncheck it to remove all labels.


2 Answers

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

like image 134
friism Avatar answered Oct 01 '22 21:10

friism


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);
}
like image 34
Aravind Asok Avatar answered Oct 01 '22 21:10

Aravind Asok