0

我想通过切换样式菜单链接访问传单绘制工具栏,以便用户一次可以绘制一个矩形(实际上这些将被插入到数据库中)。到目前为止,我管理的是用户可以在工具栏上切换,绘制一个矩形,完成后关闭工具栏,这很好,但是当用户第二次这样做时(即再次打开工具栏)绘制的矩形数量增加。我不知道为什么。有人可以解释并提供解决方案。要求是每次启用工具栏时生成一个矩形。

var map = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 18,
}).addTo(map);


var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);

var drawControl = new L.Control.Draw({
    position: 'topright',
    draw: {
            polyline: false,
            circle: false,
            marker: false,
            polygon: false,
            rect: {
                    shapeOptions: {
                            color: 'green'
                    },
            }
    }
});

var step1Enabled = 0;
$('#step1').click(function(){
      if (step1Enabled){
          map.removeControl(drawControl);
          drawnItems.clearLayers();
          step1Enabled = 0;
      }else{
          step1Enabled = 1;
          map.addControl(drawControl);
          map.on('draw:created', function (e) {
                  var type = e.layerType,
                          layer = e.layer;
                  layer.addTo(map);
                  if (type === 'rectangle') {
                      console.log(type, ' drawn');
                  }
          });
      }
});
4

1 回答 1

2

您需要清除绘制的图层。

         // event handler
         function drawCreated(e) {
            var type = e.layerType,
            layer = e.layer;
            layer.addTo(drawnItems);
            console.log(type, ' drawn', layer);
          }

          var step1Enabled = 0;
          $('#step1').click(function(){
                if (step1Enabled){
                    // remove event handler
                    map.off('draw:created', drawCreated);
                    map.removeControl(drawControl);
                    drawnItems.clearLayers();
                    step1Enabled = 0;
                }else{
                    step1Enabled = 1;
                    map.addControl(drawControl);
                    // add event handler
                    map.on('draw:created', drawCreated);
                }
          });
于 2016-06-26T17:25:15.680 回答