经纬志
首页 / MapLibre / API 文档

setPaintProperty

先看结论

只改某一层的绘制属性,颜色、透明度、宽度即时生效,不需要重设整份样式。

最后验证 2026-11-03 · MapLibre GL JS 4.x · 更新 2026-10-28 · 引用本文
map.setPaintProperty(layerId, 'fill-color', value, options?)

参数

参数类型说明
layerIdstring目标图层 id,不存在时触发 error 事件
namestring绘制属性名,需与图层类型匹配,如 fill-color
valueany字面量或表达式
options.validateboolean默认 true,校验值是否符合样式规范

传 id 而不是图层对象,是因为样式内部以 id 索引图层。 属性名写错或与图层类型不匹配(给 line 层设 fill-color)时不会抛异常,只在控制台报校验错误。

常见属性

图层类型属性作用
fillfill-color、fill-opacity、fill-outline-color填充色与描边
lineline-color、line-width、line-dasharray线色与虚实
circlecircle-radius、circle-color、circle-stroke-width圆点尺寸与描边
rasterraster-opacity、raster-brightness-min影像透明度与亮度
fill-extrusionfill-extrusion-height、fill-extrusion-color建筑高度与颜色

相关成员

成员说明
getPaintProperty(layerId, name)读取当前值,可用于撤销前先存档
setLayoutProperty(layerId, name, value)改布局属性
setFilter(layerId, filter)换要素过滤条件
getLayer(layerId)确认图层存在,避免触发 error

示例

map.setPaintProperty('world-fill', 'fill-color', '#cfe0f2');
map.setPaintProperty('world-fill', 'fill-opacity', 0.8);

/* 表达式同样可用,分类着色 */
map.setPaintProperty('world-fill', 'fill-color', [
  'match', ['get', 'CONTINENT'],
  'Asia', '#dbe7f3',
  'Europe', '#e6e0f3',
  '#e9ecef'
]);

/* 线宽随缩放变化 */
map.setPaintProperty('world-line', 'line-width', [
  'interpolate', ['linear'], ['zoom'], 2, 0.5, 6, 2
]);

/* 关闭校验可略过检查,仅在值已确定合法时使用 */
map.setPaintProperty('world-fill', 'fill-opacity', 0.6, { validate: false });

注意事项

属性值变化会立即重绘,但同一帧内连续改多个属性会各自触发一次更新。 批量调整时把改动放在同一个回调里,浏览器合并渲染后只画一帧。

透明度为 0 与 visibility: 'none' 效果相似,代价不同: 前者仍然参与绘制,后者直接跳过。纯隐藏用布局属性更省。

运行时改样式不会写回数据源。setPaintProperty 只影响当前会话,刷新页面后回到样式文件里的定义。需要持久化就得 自己记录用户选择,加载时重新应用。

引用本文

经纬志(2026)。《setPaintProperty》。https://www.jingweizhi.com/maplibre/api/set-paint-property.html(访问日期 2026-11-03)。