【问题标题】:Delete the last 2 additions to a featuregroup in Leaflet删除 Leaflet 中特征组的最后 2 个添加项
【发布时间】:2022-01-13 15:43:42
【问题描述】:

我有一个添加圆圈标记和路径的功能组——它们是按顺序添加的,我需要一种方法来创建一个函数,该函数将在每次单击时删除 _layers 中的最后 (2) 个函数。

我尝试过切片,但它不起作用,因为它不是真正的数组。

关于如何进行的任何想法?我一直在搜索 stackoverflow,但找不到与我正在尝试做的事情相匹配的任何内容。

【问题讨论】:

  • 代码在哪里?制作一个工作代码的小样本并将其放在这里,也许有人会提供帮助。最重要的是,添加到 codepen、codesandbox 或其他网站。

标签: javascript jquery leaflet


【解决方案1】:

让我们简单地参考 Leaflet 文档:

您可以使用methods the layerGroup/featureGroup provides 从组中删除最后两层。

Leaflet 的 featureGroup is an extension of the layerGroup,所以所有这些都适用于 featureGroup

所以,假设您的图层设置如下:

// Layers:
var layers = L.layerGroup().addTo(map);

var marker = L.marker([51.5, -0.09]).addTo(layers);
var circle = L.circle([51.508, -0.11], {
  color: 'red',
  fillColor: '#f03',
  fillOpacity: 0.5,
  radius: 500,
}).addTo(layers);
var polygon = L.polygon([
  [51.509, -0.08],
  [51.503, -0.06],
  [51.51, -0.047],
]).addTo(layers);

您可以使用那些layerGroup 方法来删​​除数组的最后两个元素:

// Pass the layerGroup to the function
function removeLastTwo(layerGroup) {
  // Use getLayers to get the array
  var layerArr = layerGroup.getLayers();
  var minusOne = layerArr.length - 1;
  var minusTwo = layerArr.length - 2;
  // Use eachLayer to iterate the layerGroup
  layerGroup.eachLayer((layer) => {
    // Grab the index of the layer
    var layerIndex = layerArr.indexOf(layer);
    // Remove the last two elements of the layerGroup array
    if (layerIndex === minusOne || layerIndex === minusTwo) {
      layerGroup.removeLayer(layer);
    }
  });
}

Here is a live example,将此函数附加到按钮的单击事件侦听器。

【讨论】:

  • 有一个微妙之处可以使这种方法在“最后两个”中表现出意外:getLayers 和 eachLayer 可能不会按插入顺序进行迭代。传单图层组在内部使用地图/字典来存储其子图层,并将这些图层的标记 ID(整数)作为键。因此迭代顺序基于这些整数 id(JS 规范)。在简单的情况下,子图层的创建顺序与插入顺序相同。但在更复杂的情况下无法保证。
猜你喜欢
  • 1970-01-01
  • 2017-11-21
  • 2019-10-28
  • 1970-01-01
  • 1970-01-01
  • 2020-10-07
  • 2011-09-05
  • 2021-05-08
相关资源
最近更新 更多