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 圆点图层