首页 > 解决方案 > 单击按钮时从地图框中删除所有标记

问题描述

我知道有一个命令“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'
});

然后我的Function1...

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() {... }

标签: javascriptbuttonmapboxmarker

解决方案


你可以这样尝试:

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

   //define that to delete or todo here

});

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


推荐阅读