MapBoxGL 问题记录

367 阅读1分钟

一、removeLayer 删除图层后再次添加相同id的图层会报错图层还存在

  • 删除图层后还需要使用removeSource删除图层源
  • 为添加图层源,mapbox-gl 会自动创建和addLayer 图层相同ID的源
  • 需要删除图层源
   const lineLayer = {
        id: 'lineBox',
        type: 'line',
        source: {
          type: 'geojson',
           {
            type: 'FeatureCollection',
            features: [
              {
                type: 'Feature',
                geometry: {
                  type:'LineSting',
                  coordinates: [],
                },
              },
            ],
          },
        },
        paint: {
          'line-color':'red',
         
        },
      }

      scene.addLayer(lineLayer);
      
      // 删除
      if (scene && scene.getLayer('lineBox')) scene.removeLayer('lineBox')
      if (scene && scene.getSource('lineBox')) scene.removeSource('lineBox');
      

二、 鼠标样式

scene.getCanvas().style.cursor = 'pointer';

scene.getCanvas().style.cursor = '';

三、两个图层叠加,点击重合部分都触发事件解决方案

原因: 事件冒泡导致

解决方法:

// 理出打印顺序,必须将上层的打印触发事件写在上面
// 在上层的layer中写入:
 scene.on('click', 'up-layer', (e) => {
      e.preventDefault()
 });

// 阻止默认事件  
// 在下面的layer中我们可以打印他的e,可以看到_defaultPrevented: false,在layer中写入

scene.on('click', 'down-layer', (e) => {
  if (e.defaultPrevented) return;
});

四、text-field 字体报错问题

  • mapboxGl 默认会给出一个fallback字体,只可使用中文
  • 如使用带特殊符号字体、数字等;需要使用glyphs字段
  • glyphs:可使用官网中默认字体,也可以使用本地化glyphs字体
  • 字体格式需转换成pbf文件格式
style: {
    version: 8,
    glyphs: '/fonts/glyphs/{fontstack}/{range}.pbf',    
}

  
layout: {
  'text-field': ['get', 'name'],
  'text-font': ['Alibaba-PuHuiTi Heavy'],
  'text-offset': [0, -0.7],
  'text-anchor': 'bottom',
  "text-size": 12
},
 

五、如何关闭所有popup 弹窗

  • mapbox-gl 只有关闭单个popup方法remove
  • 允许您监听地图上的事件(并手动触发它们)
//a.js
const popup = new mapboxgl.Popup({  anchor: 'bottom' }).setDOMContent('<h5>Hello</h5>').setLngLat(feature.geometry.coordinates).addTo(map);

// 自定义监听事件
map.on('closeAllPopups', () => {
  popup.remove();
});

// uitls.js 触发closeAllPopups 监听事件
const removePopupFun = (map) => {
  map.fire('closeAllPopups');
}

六、如何根据图层自动缩放边界

  • 使用fitBounds 方法
// coordinates 经纬度数组
  scene.fitBounds(coordinates, {
  // 可定制样式
    padding: 20
  })