单击按钮时,从地图框中删除所有标记

时间:2019-01-13 17:36:38

标签: javascript button mapbox clear marker

我知道有一个命令“ marker.remove()”,允许我在将标记添加到地图后立即删除它。以下代码是for循环的一部分:

      var marker = new mapboxgl.Marker(el)
      .setLngLat(markeryellowhalf.geometry.coordinates)
      .addTo(map);
      //marker.remove();

但是我的想法是单击一个调用新功能的按钮。该功能应该做的第一件事就是删除(或隐藏)所有标记。

可以使用哪个命令启动此功能?当然,“ marker.remove()”在这里不起作用。

这是我的地图对象:

    var map = new mapboxgl.Map({    
    style: 'mapbox://styles/mapbox/dark-v9',
    center: [30, 0],
    zoom: 1.2,
    // pitch: 45,
    // bearing: -17.6,
    container: 'map'
});

然后是myFunction1 ...

function myFunction1(){
.
.
.
switch (statusArray1[c]){
    case "existing [completed]":
    geojson.features.forEach(function(markeryellow) {

      // create a HTML element for each feature
      var el = document.createElement('div');
      el.className = 'markeryellow';

      // make a markeryellow for each feature and add to the map
    var marker = new mapboxgl.Marker(el)
      .setLngLat(markeryellow.geometry.coordinates)
      .setPopup(new mapboxgl.Popup({ offset: 25 }) // add popups
      .setHTML('<h3>' + markeryellow.properties.title + '</h3><p>' + markeryellow.properties.description + '</p>'))
      .addTo(map);
      //marker.remove();
    });
    break;
    case "under construction [on hold]":
    case "under construction [foundation work]":
    case "under construction [frame assembly]":
    case "under construction [topped out]":
    geojson.features.forEach(function(markeryellowhalf) {

      // create a HTML element for each feature
      var el = document.createElement('div');
      el.className = 'markeryellowhalf';

      // make a markeryellowhalf for each feature and add to the map
        var marker = new mapboxgl.Marker(el)
      .setLngLat(markeryellowhalf.geometry.coordinates)
      .setPopup(new mapboxgl.Popup({ offset: 25 }) // add popups
      .setHTML('<h3>' + markeryellowhalf.properties.title + '</h3><p>' + markeryellowhalf.properties.description + '</p>'))
      .addTo(map);
      //marker.remove();
    });



    break;
}

}

}

然后出现myFunction2(){... }

1 个答案:

答案 0 :(得分:0)

您可以这样尝试:

map.on('click', function (e) {

   //define that to delete or todo here

});

但是要获得更准确的答案,我需要更多信息,例如html/css和您的map object