You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通过下拉菜单添加新图层时,如何移除旧的L.GeoJSON图层?

解决方案

问题出在你每次调用_callBack时都会新建一个L.LayerGroup并添加到地图,旧的图层组并没有从地图上移除,导致每次选新国家都会叠加新图层。

解决方法是把图层组作为实例的持久化属性,而不是每次函数内临时创建:

  1. 在类的构造函数中初始化一个全局的图层组,并添加到地图:
constructor() {
  // 其他初始化代码...
  this.#countryLayerGroup = new L.LayerGroup().addTo(this.#map);
}
  1. 修改_callBack函数,复用这个图层组,每次先清空再添加新图层:
_callBack(coords) {
  const map = this.#map;
  const myStyle = {
    color: "#80ff00",
    weight: 3,
    opacity: 0.5,
  };
  if (coords) {
    // 清空已有的图层组
    this.#countryLayerGroup.clearLayers();
    // 创建新的GeoJSON图层并添加到持久化图层组
    const sMap = new L.GeoJSON(coords, { style: myStyle });
    this.#countryLayerGroup.addLayer(sMap);
    // 缩放至新图层范围
    map.fitBounds(sMap.getBounds());
  }
}

这样每次选择新国家时,旧的GeoJSON图层会被先清空,再添加新的,就不会出现图层叠加的问题了。

内容的提问来源于stack exchange,提问作者foster11112022

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 13:52:05