11. Symbol 符号图层

4 阅读1分钟

11. Symbol 符号图层

概述

Symbol 图层用于渲染文字标注和图标,是最复杂也最常用的图层类型之一。本节学习:

  • 文字标注(text-field / text-size / text-font)
  • 图标显示(icon-image / icon-size)
  • Sprite 雪碧图机制
  • 自定义图标(addImage)
  • 碰撞检测

文字标注

map.addLayer({
  id: 'labels',
  type: 'symbol',
  source: 'my-source',
  layout: {
    'text-field': ['get', 'name'],
    'text-size': 14,
    'text-anchor': 'center',
    'text-offset': [0, 0]
  },
  paint: {
    'text-color': '#333',
    'text-halo-color': '#fff',
    'text-halo-width': 1.5
  }
})

常用 Layout 属性

属性说明
text-field文本内容(支持表达式)
text-size字体大小
text-font字体名称数组
text-anchor锚点位置
text-offset偏移 [x, y]
text-max-width最大宽度(自动换行)
text-rotation-alignment旋转对齐方式
text-allow-overlap允许文字重叠

常用 Paint 属性

属性说明
text-color文字颜色
text-halo-color文字光晕颜色
text-halo-width光晕宽度
text-opacity透明度

图标显示

map.addLayer({
  id: 'icons',
  type: 'symbol',
  source: 'my-source',
  layout: {
    'icon-image': 'marker-icon',
    'icon-size': 0.5,
    'icon-anchor': 'bottom'
  }
})

自定义图标(addImage)

// 方法1:加载图片
map.loadImage('https://example.com/icon.png', (error, image) => {
  if (error) throw error
  map.addImage('custom-icon', image!)
})

// 方法2:使用 HTMLCanvasElement
const canvas = document.createElement('canvas')
// ... 绘制图标
map.addImage('canvas-icon', canvas)

碰撞检测

默认情况下 MapLibre 会自动处理标注碰撞:

layout: {
  'icon-allow-overlap': false,    // 不允许图标重叠(默认)
  'text-allow-overlap': false,    // 不允许文字重叠(默认)
  'icon-ignore-placement': false, // 不忽略其他元素的位置
  'text-ignore-placement': false,
  'symbol-sort-key': ['get', 'priority']  // 排序优先级
}

本课小结

  • Symbol 图层渲染文字和图标
  • text-halo 添加文字光晕提高可读性
  • addImage 可注册自定义图标
  • 碰撞检测自动隐藏重叠标注

📌 上一节:10. Line 线图层 📌 下一节:12. Circle 圆点图层