且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Google Maps API v3删除所有折线

更新时间:2023-02-14 14:24:23

您必须做 polyline.setMap( null),这将从地图中删除该行。 文档


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

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