09. Fill 填充图层
概述
Fill 图层用于渲染多边形(Polygon)区域,是地图中最常用的图层类型之一。本节学习:
- Fill 图层的基本用法
- fill-color / fill-opacity / fill-outline-color / fill-pattern 属性
- 行政区域填色地图实战
基本用法
map.addLayer({
id: 'area-fill',
type: 'fill',
source: 'my-geojson',
paint: {
'fill-color': '#1890ff',
'fill-opacity': 0.5
}
})
Paint 属性
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
fill-color | color | #000000 | 填充颜色 |
fill-opacity | number | 1 | 填充透明度(0~1) |
fill-outline-color | color | 无 | 轮廓线颜色(需启用抗锯齿) |
fill-pattern | string | 无 | 填充图案(sprite 中的图标名) |
fill-antialias | boolean | true | 是否启用抗锯齿 |
fill-translate | [x, y] | [0, 0] | 几何偏移(像素) |
fill-color 示例
paint: {
// 固定颜色
'fill-color': '#ff0000',
// 数据驱动 — 根据属性值设置颜色
'fill-color': [
'match', ['get', 'level'],
'高', '#ff4d4f',
'中', '#faad14',
'低', '#52c41a',
'#ccc' // 默认值
]
}
fill-opacity 示例
paint: {
'fill-opacity': 0.5,
// 根据缩放级别渐变
'fill-opacity': [
'interpolate', ['linear'], ['zoom'],
8, 0.8,
14, 0.3
]
}
fill-outline-color
paint: {
'fill-color': '#1890ff',
'fill-opacity': 0.3,
'fill-outline-color': '#1890ff' // 轮廓线不受 opacity 影响
}
💡
fill-outline-color只在fill-antialias: true时有效。对于更灵活的边框样式,建议额外添加 Line 图层。
fill-pattern
// 需要先通过 sprite 或 addImage 加载图案
map.addImage('stripe', stripeImage)
paint: {
'fill-pattern': 'stripe'
}
Layout 属性
| 属性 | 说明 |
|---|---|
visibility | 'visible' 或 'none',控制图层显隐 |
fill-sort-key | 用于控制要素的绘制排序 |
行政区域填色地图实战
// 1. 添加行政区划 GeoJSON
map.addSource('districts', {
type: 'geojson',
data: districtsGeoJSON
})
// 2. 添加填充图层(分级设色)
map.addLayer({
id: 'district-fill',
type: 'fill',
source: 'districts',
paint: {
'fill-color': [
'interpolate', ['linear'], ['get', 'population'],
0, '#f0f9e8',
500000, '#bae4bc',
1000000, '#7bccc4',
5000000, '#43a2ca',
10000000, '#0868ac'
],
'fill-opacity': 0.7
}
})
// 3. 添加边框图层
map.addLayer({
id: 'district-border',
type: 'line',
source: 'districts',
paint: {
'line-color': '#333',
'line-width': 1
}
})
本课小结
- Fill 图层渲染多边形区域
fill-color支持固定颜色和数据驱动表达式fill-outline-color不受 opacity 影响,适合显示边框- 复杂边框建议用单独的 Line 图层
- 结合表达式可实现分级设色地图
📌 上一节:08. 矢量瓦片与栅格瓦片 📌 下一节:10. Line 线图层