javascriptgoogle-mapsgoogle-maps-api-3google-polyline

SetMap(null) not working with markers in google maps v3


I'm creating a web app where on page load multiple polylines are drawn from one point to many. Their corresponding markers are also drawn. On change in dropdown list the polylines & markers should dissapear.

Current code output..

google maps ouput

On changing the dropdown list the markers and the corresponding polylines should dissapear but currently only markers are dissapearing, not polylines

HTML code...

   <div class="filter-set">
    <label for="ship-select">See most popular destinations from an area:</label>
    <select id="type" onchange="filterAirports(this.value);">
    <option value="-1">Any</option>
    <option value="0">20001, Northwest Washington, Washington</option>
    <option value="1">512, 2001 Pennsylvania Ave NW, Washington, DC</option>  
</select><br/><br/>
</div>
<div id="map_wrapper">
    <div id="us_map" class="mapping"></div>
</div>

JavaScript Code...

    var gmarkers1 = [];
    var airport_location = [];
    var marker_element = [];
    var polyline=null,polyline1=null;
    var infowindow = new google.maps.InfoWindow({
        content: ''
    });
    var activities = document.getElementById("type");

    // start coordinates
    var start = [['20001, Northwest Washington, Washington',38.912068, -77.019023,1],
                ['512, 2001 Pennsylvania Ave NW, Washington, DC',38.90167,-77.045169,2]
                //['2000 H St NW, Washington, DC',38.89856,-77.045791]
                ];

    //2d array having multiple points for each point above
    airport_location = [[
        ['800 Gregorio Drive, Montgomery Knolls, Silver Spring', 39.009814, -76.99548, 1,2331], //
        ['9200 Whitney Street, Silver Spring', 39.005551, -77.003279, 2,2320], //
        ['100 Melbourne Avenue, Silver Spring', 39.006549, -77.011154, 3,2265], //
        ['8600 Lancaster Drive, Bethesda', 38.996859 ,  -77.088684, 4,2186], //
        ['8600 Irvington Avenue, Bradmoor, Bethesda', 38.996353 , -77.118253, 5,2159], //
        ['2400 Lyttonsville Place, Silver Spring', 38.998812, -77.052447, 6,2144], //
        ['8500 Glenville Road, Takoma Park', 38.994632, -76.993937, 7,2111], //
        ['8600 Cunningham Drive, Berwyn Heights', 38.991265 , -76.913815, 8,2097], //
        ['4800 Del Ray Avenue, Woodmont Triangle, Bethesda', 38.991144 , -77.097584, 9,2089],//
        ['8600 22nd Avenue, Hyattsville',  38.997182 , -76.968822, 10,2071] //
    ],
                    [
        ['9500 Elvis Lane, Lanham-Seabrook, Goddard', 38.985575 , -76.844996, 1,2547], //
        ['2700 Phelps Avenue, District Heights', 38.851711, -76.868447, 2,2469], //
        ['1800 Metzerott Road, Adelphi', 39.004447 , -76.977798, 3,2459], //
        ['3800 Forestville Road, District Heights', 38.836892 , -76.875601, 4,2366], //
        ['600 Cappy Avenue, Capitol Heights', 38.879616, -76.887745, 5,2360], //
        ['1700 Ritchie Road, District Heights', 38.866842, -76.862023, 6,2359], //
        ['6800 Asset Drive, Landover, 13, Kent, Prince George County, Maryland, United States, 20785)', 38.907013 , -76.890744, 7,2341], //
        ['5900 Cherrywood Lane, Greenbelt', 39.004776, -76.907918, 8,2319], //
        ['8600 22nd Avenue, Hyattsville', 38.997182, -76.968822, 9,2279],//
        ['1100 Valley Drive, College Park', 39.175554, -78.17089, 10,2274] //
    ]];

     //gmarkers1 = airport_location.slice();

    //Function to plot map intially on page load


    function initialize() {
        var center = new google.maps.LatLng(38.8977, -77.0365);
        var mapOptions = {
            zoom: 8,
            center: center,
            //mapTypeId: google.maps.MapTypeId.TERRAIN
        };

        map = new google.maps.Map(document.getElementById('us_map'), mapOptions);
        for (i = 0; i < airport_location.length; i++) {
            //addMarker(start[i]);
            for(var j=0; j < airport_location[i].length; j++){
                //console.log("Marker array is:" +airport_location[i][j]);
                addMarker(airport_location[i][j],i,j);
            }

        }
        console.log("gmarker array is: "+gmarkers1.length)

        var bounds = new google.maps.LatLngBounds();
        var paths = [];

        for (var i=0; i < airport_location.length; i++){
            for(var j=0; j < airport_location[i].length; j++){
        //  var startCoords = start[i].split(",");
            var startPt = new google.maps.LatLng(start[i][1],start[i][2]);
            //var endCoords = end[i].split(",");
            var endPt = new google.maps.LatLng(airport_location[i][j][1],airport_location[i][j][2]);
            if(i ==0){
                calcRoute(startPt, endPt);
                //paths.push([startPt, endPt]);
            }else{
            calcRoute1(startPt, endPt);
            }
            bounds.extend(startPt);
            bounds.extend(endPt);

            }
        }
        map.fitBounds(bounds);

    }

    // Initialize Google Maps API
    initialize();


    //Function to plot airports on the map



    function calcRoute(source,destination){
    polyline = new google.maps.Polyline({
        path: [source, destination],
        strokeColor: 'red',
        strokeWeight: 2,
        strokeOpacity: 1
    });

    polyline.setMap(map); 
    }

    activities.addEventListener("change", function() {
        console.log("change called")
        polyline.setMap(null);
        //polyline = null;
        console.log("polyline "+polyline);
        polyline1.setMap(null);
        //polyline.setPath([]);
    });

    function calcRoute1(source,destination){
    polyline1 = new google.maps.Polyline({
        path: [source, destination],
        strokeColor: 'red',
        strokeWeight: 2,
        strokeOpacity: 1
    });

    polyline1.setMap(map); 


    }

    function addMarker(marker,i,j) {
    console.log("i value is :"+i)
        var elevation = marker[4];
        var title = marker[0];
        var pos = new google.maps.LatLng(marker[1], marker[2]);
        var content = marker[0];

        marker1 = new google.maps.Marker({
            title: title,
            position: pos,
            elevation: elevation,
            map: map
        });
        //console.log("marker is: "+marker1)
        gmarkers1.push(marker1);

        // Fuction to display text on click
        google.maps.event.addListener(marker1, 'click', (function (marker1, content) {
            return function () {
            // console.log('Gmarker 1 gets pushed');
                infowindow.setContent(content);
                infowindow.open(map, marker1);
                map.panTo(this.getPosition());
            }
        })(marker1, content));
    }

    // function to add/remove markers based on filter

    filterAirports = function (elevation) {
    console.log("Condition: "+elevation)
            for (i = 0; i < gmarkers1.length; i++) {
            marker = gmarkers1[i];
            if(elevation == 0){
                if (i >=0 && i<= 9) {
                    marker.setVisible(true);
                }
                else {
                    marker.setVisible(false);

                }
            }else if(elevation == 1){
                if (i >=10 && i<= 19) {
                    marker.setVisible(true);
                }
                else {
                    marker.setVisible(false);
                }
            }else if(elevation == 2){

            }else if(elevation == -1){
                marker.setVisible(true);
            }

        }
    }

As you can see in the code above, even after calling the setMap(null) code in the dropdown's event listener the polylines are not dissapearing.

Can't understand where I'm going wrong.. Spent 3 hours on this issue...Please Help!!

Edit 1: Added complete code to resolve few errors. On dropdown event change only the last polyline of point "1100 Valley Drive," is dissapearing but not reappearing on selecting some other option.

Edit 2: JS fiddle https://jsfiddle.net/Lucy1/8qb0w1t4/ Basically I want the polylines, markers to appear & dissapear based on dropdown value selected. Marker code is working, polylines code is not!


Solution

  • You need to save the polylines in an array like you do the markers:

    // global variables
    var gmarkers1 = [];
    var polylines = []; // add this
    
    function calcRoute1(source, destination) {
      polyline1 = new google.maps.Polyline({
        path: [source, destination],
        strokeColor: 'red',
        strokeWeight: 2,
        strokeOpacity: 1
      });
    
      polyline1.setMap(map);
      polylines.push(polyline1);
    }
    

    Then when you filter them:

    filterAirports = function(elevation) {
      console.log("Condition: " + elevation)
      for (i = 0; i < gmarkers1.length; i++) {
        marker = gmarkers1[i];
        // assume same number of polylines as markers and are in the same order in the arrays
        polyline = polylines[i];
        if (elevation == 0) {
          if (i >= 0 && i <= 9) {
            marker.setVisible(true);
            polyline.setMap(map);
          } else {
            marker.setVisible(false);
            polyline.setMap(null);
          }
        } else if (elevation == 1) {
          if (i >= 10 && i <= 19) {
            marker.setVisible(true);
            polyline.setMap(map);
          } else {
            marker.setVisible(false);
            polyline.setMap(null);
          }
        } else if (elevation == 2) {
    
        } else if (elevation == -1) {
          marker.setVisible(true)
          polyline.setMap(map);
        }
      }
    }
    

    proof of concept fiddle

    code snippet:

    var map;
    var gmarkers1 = [];
    var polylines = [];
    var airport_location = [];
    var marker_element = [];
    var polyline = null,
      polyline1 = null;
    var infowindow = new google.maps.InfoWindow({
      content: ''
    });
    var activities = document.getElementById("type");
    
    // start coordinates
    var start = [
      ['20001, Northwest Washington, Washington', 38.912068, -77.019023, 1],
      ['512, 2001 Pennsylvania Ave NW, Washington, DC', 38.90167, -77.045169, 2]
      //['2000 H St NW, Washington, DC',38.89856,-77.045791]
    ];
    
    //2d array having multiple points for each point above
    airport_location = [
      [
        ['800 Gregorio Drive, Montgomery Knolls, Silver Spring', 39.009814, -76.99548, 1, 2331], //
        ['9200 Whitney Street, Silver Spring', 39.005551, -77.003279, 2, 2320], //
        ['100 Melbourne Avenue, Silver Spring', 39.006549, -77.011154, 3, 2265], //
        ['8600 Lancaster Drive, Bethesda', 38.996859, -77.088684, 4, 2186], //
        ['8600 Irvington Avenue, Bradmoor, Bethesda', 38.996353, -77.118253, 5, 2159], //
        ['2400 Lyttonsville Place, Silver Spring', 38.998812, -77.052447, 6, 2144], //
        ['8500 Glenville Road, Takoma Park', 38.994632, -76.993937, 7, 2111], //
        ['8600 Cunningham Drive, Berwyn Heights', 38.991265, -76.913815, 8, 2097], //
        ['4800 Del Ray Avenue, Woodmont Triangle, Bethesda', 38.991144, -77.097584, 9, 2089], //
        ['8600 22nd Avenue, Hyattsville', 38.997182, -76.968822, 10, 2071] //
      ],
      [
        ['9500 Elvis Lane, Lanham-Seabrook, Goddard', 38.985575, -76.844996, 1, 2547], //
        ['2700 Phelps Avenue, District Heights', 38.851711, -76.868447, 2, 2469], //
        ['1800 Metzerott Road, Adelphi', 39.004447, -76.977798, 3, 2459], //
        ['3800 Forestville Road, District Heights', 38.836892, -76.875601, 4, 2366], //
        ['600 Cappy Avenue, Capitol Heights', 38.879616, -76.887745, 5, 2360], //
        ['1700 Ritchie Road, District Heights', 38.866842, -76.862023, 6, 2359], //
        ['6800 Asset Drive, Landover, 13, Kent, Prince George County, Maryland, United States, 20785)', 38.907013, -76.890744, 7, 2341], //
        ['5900 Cherrywood Lane, Greenbelt', 39.004776, -76.907918, 8, 2319], //
        ['8600 22nd Avenue, Hyattsville', 38.997182, -76.968822, 9, 2279], //
        ['1100 Valley Drive, College Park', 39.175554, -78.17089, 10, 2274] //
      ]
    ];
    
    //gmarkers1 = airport_location.slice();
    
    //Function to plot map intially on page load
    
    
    function initialize() {
      var center = new google.maps.LatLng(38.8977, -77.0365);
      var mapOptions = {
        zoom: 8,
        center: center,
        //mapTypeId: google.maps.MapTypeId.TERRAIN
      };
    
      map = new google.maps.Map(document.getElementById('us_map'), mapOptions);
      for (i = 1; i < airport_location.length; i++) {
        //addMarker(start[i]);
        for (var j = 0; j < airport_location[i].length; j++) {
          //console.log("Marker array is:" +airport_location[i][j]);
          addMarker(airport_location[i][j], i, j);
        }
    
      }
      console.log("gmarker array is: " + gmarkers1.length)
    
      var bounds = new google.maps.LatLngBounds();
      var paths = [];
    
      for (var i = 1; i < airport_location.length; i++) {
        for (var j = 0; j < airport_location[i].length; j++) {
          //  var startCoords = start[i].split(",");
          var startPt = new google.maps.LatLng(start[i][1], start[i][2]);
          //var endCoords = end[i].split(",");
          var endPt = new google.maps.LatLng(airport_location[i][j][1], airport_location[i][j][2]);
          if (i == 0) {
            calcRoute(startPt, endPt);
            //paths.push([startPt, endPt]);
          } else {
            calcRoute1(startPt, endPt);
          }
          bounds.extend(startPt);
          bounds.extend(endPt);
    
        }
      }
      map.fitBounds(bounds);
    
    }
    
    // Initialize Google Maps API
    initialize();
    
    
    //Function to plot airports on the map
    
    
    
    function calcRoute(source, destination) {
      polyline = new google.maps.Polyline({
        path: [source, destination],
        strokeColor: 'red',
        strokeWeight: 2,
        strokeOpacity: 1
      });
    
      polyline.setMap(map);
      polylines.push(polyline);
    }
    
    /* activities.addEventListener("change", function() {
      console.log("change called")
      polyline.setMap(null);
      polyline = null;
      console.log("polyline " + polyline);
      //  
      //polyline.setPath([]);
    }); */
    
    function calcRoute1(source, destination) {
      polyline1 = new google.maps.Polyline({
        path: [source, destination],
        strokeColor: 'red',
        strokeWeight: 2,
        strokeOpacity: 1
      });
    
      polyline1.setMap(map);
      polylines.push(polyline1);
    }
    
    function addMarker(marker, i, j) {
      console.log("i value is :" + i)
      var elevation = marker[4];
      var title = marker[0];
      var pos = new google.maps.LatLng(marker[1], marker[2]);
      var content = marker[0];
    
      marker1 = new google.maps.Marker({
        title: title,
        position: pos,
        elevation: elevation,
        map: map
      });
      //console.log("marker is: "+marker1)
      gmarkers1.push(marker1);
    
      // Fuction to display text on click
      google.maps.event.addListener(marker1, 'click', (function(marker1, content) {
        return function() {
          // console.log('Gmarker 1 gets pushed');
          infowindow.setContent(content);
          infowindow.open(map, marker1);
          map.panTo(this.getPosition());
        }
      })(marker1, content));
    }
    
    // function to add/remove markers based on filter
    
    filterAirports = function(elevation) {
      console.log("Condition: " + elevation)
      for (i = 0; i < gmarkers1.length; i++) {
        marker = gmarkers1[i];
        // assume same number of polylines as markers and are in the same order in the arrays
        polyline = polylines[i];
        if (elevation == 0) {
          // polyline.setMap(null);
          if (i >= 0 && i <= 9) {
            marker.setVisible(true);
            polyline.setMap(map);
          } else {
            marker.setVisible(false);
            polyline.setMap(null);
          }
        } else if (elevation == 1) {
          if (i >= 10 && i <= 19) {
            marker.setVisible(true);
            polyline.setMap(map);
          } else {
            marker.setVisible(false);
            polyline.setMap(null);
          }
        } else if (elevation == 2) {
    
        } else if (elevation == -1) {
          marker.setVisible(true)
          polyline.setMap(map);
        }
      }
    }
    // google.maps.event.addDomListener(window, "load", initialize);
    html,
    body,
    #map_wrapper,
    #us_map {
      height: 100%;
      width: 100%;
      margin: 0px;
      padding: 0px
    }
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
    <div class="filter-set">
      <label for="ship-select">See most popular destinations from an area:</label>
      <select id="type" onchange="filterAirports(this.value);">
        <option value="-1">Any</option>
        <option value="0">20001, Northwest Washington, Washington</option>
        <option value="1">512, 2001 Pennsylvania Ave NW, Washington, DC</option>
      </select>
      <br/>
      <br/>
    </div>
    <div id="map_wrapper">
      <div id="us_map" class="mapping"></div>
    </div>