mapbox底图切换后原图层消失

279 阅读1分钟

mapbox底图图层切换之后,其他图层消失了

消失原因

  • mapbox-gl 中的layers和sources是在style中绑定的,当直接以字符串的形式修改底图的时候,相关的layers和sources会被清空;
  • 图层添加是在load里面,load只会在第一次加载的时候执行,setStyle之后没有重新添加;

解决方法

用load[initAdd]+styledata[afterCheckAdd]❌

  • layer和source还原法
  • 在重置底图样式之前需要记录下原样式中的source和layers,然后setStyle,此方法会触发 styledatastyle改变的回调,在回调中将sources和layers加入新样式
map.on('styledata', mapStyleChange);

const mapStyleChange = () => {
    if (!mapSwitchData.current) return;
    const mapJSON = map.getStyle();
    if (mapSwitchData.current) {
      const { sources, layers } = mapSwitchData.current;
      console.log(sources, layers);
      mapJSON.sources = sources;
      mapJSON.layers.push(...layers);
    }
    mapSwitchData.current = null;
    map.setStyle(mapJSON);
};
const mapStyleSwitch = (value) => {
    const style = map.getStyle();
    mapSwitchData.current = {
      sources: style.sources,
      layers: style.layers.slice(83),//项目中没有修改原有图层的层级,如果有相关的影响,可以给项目图层加metadata信息用于筛选
      //const layers = style.layers.filter((v) => v?.metadata === 'custom');
    };
    map.setStyle(value);
};

用style.load回调 ✔

  • 修改图层添加的时机,所有图层的添加都放在style.load里面,在setStyle之后,style.load回调会重新加载

参考:mapbox事件

安装react-map-gl💯

  • 以标签的形式展示Source和Layer,Map的style用state控制
  • 在更新图层的Source资源可以在适当的时机调用map.getSource('X')?.reload!();或者用state控制source并给Source标签添加key