SetMap(null)无法使用google maps v3

时间:2017-12-04 14:08:42

标签: javascript google-maps google-maps-api-3 google-polyline

我正在创建一个网页应用,其中页面加载多个折线从一个点到多个。还绘制了它们相应的标记。在下拉列表中更改折线和&标记应该消失。

当前代码输出 ..

google maps ouput

在更改下拉列表时,标记和相应的折线应该消失,但目前只有标记消失,而不是折线

HTML代码 ...

   <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代码 ...

    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);
            }

        }
    }

正如您在上面的代码中看到的,即使在下拉列表的事件侦听器中调用setMap(null)代码之后,折线也不会消失。

无法理解我出错的地方..在这个问题上花了3个小时......请帮助!!

修改1 :  添加完整代码以解决一些错误。在下拉事件更改时,只有点“1100 Valley Drive”的最后一条折线消失,但在选择其他选项时不再出现。

编辑2 : JS小提琴https://jsfiddle.net/Lucy1/8qb0w1t4/ 基本上我想要折线,标记出现&amp;基于所选下拉值的消失。标记代码正常,折线代码不行!

1 个答案:

答案 0 :(得分:0)

您需要像使用标记一样将折线保存在数组中:

// 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);
}

然后当你过滤它们时:

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

代码段

&#13;
&#13;
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);
&#13;
html,
body,
#map_wrapper,
#us_map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
&#13;
<script src="https://maps.googleapis.com/maps/api/js?"></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>
&#13;
&#13;
&#13;