经纬志
首页 / OpenLayers / API 文档

Style

先看结论

样式容器。把填充、描边、点符号和文字组合在一起,决定一个要素画成什么样。

最后验证 2026-11-03 · OpenLayers 10.3.1 · 更新 2026-10-27 · 引用本文
new ol.style.Style(options)

构造参数

参数说明生效的几何
fillol.style.Fill,面填充Polygon、Circle
strokeol.style.Stroke,线或边框LineString、Polygon
image点符号,如 ol.style.CirclePoint
textol.style.Text,文字标注全部
zIndex同一要素多组样式时的绘制顺序—
geometry用要素的其他属性作为绘制几何—
var style = new ol.style.Style({
  fill: new ol.style.Fill({ color: 'rgba(31,95,208,0.15)' }),
  stroke: new ol.style.Stroke({ color: '#1f5fd0', width: 2 }),
  image: new ol.style.Circle({
    radius: 6,
    fill: new ol.style.Fill({ color: '#1f5fd0' }),
    stroke: new ol.style.Stroke({ color: '#ffffff', width: 2 })
  }),
  text: new ol.style.Text({
    text: '标注',
    offsetY: -16,
    font: '12px sans-serif',
    fill: new ol.style.Fill({ color: '#16181d' }),
    stroke: new ol.style.Stroke({ color: '#ffffff', width: 3 })
  })
});

四个字段可以同时给,OpenLayers 会按几何类型挑用得上的一部分。 点要素只用到 image 和 text, 线和面用 stroke,面再加 fill。

一组样式不够时返回数组

样式函数返回数组时,同一个要素会按顺序绘制多次。 典型用法是先画一个白色外圈做描边,再画彩色内圈:

function styleFunction(feature) {
  return [
    new ol.style.Style({
      image: new ol.style.Circle({
        radius: 9,
        fill: new ol.style.Fill({ color: 'rgba(255,255,255,0.85)' })
      })
    }),
    new ol.style.Style({
      image: new ol.style.Circle({
        radius: 6,
        fill: new ol.style.Fill({ color: '#d0453a' })
      })
    }),
    new ol.style.Style({
      text: new ol.style.Text({ text: feature.get('name'), offsetY: -16 })
    })
  ];
}

常用方法

方法说明
clone()深拷贝,改副本不影响原样式
getFill() / setFill(f)读写填充
getStroke() / setStroke(s)读写描边
getImage() / setImage(i)读写点符号
getText() / setText(t)读写文字
getZIndex() / setZIndex(z)读写层内顺序

运行时改样式对象不会自动重绘,因为样式实例本身没有绑定图层。 改了 style.getFill().setColor() 之后, 需要调用 layer.changed() 让图层重新取样式。

clone() 是深拷贝,克隆后修改文字或颜色不会污染原样式。 在样式函数里基于一个模板克隆再改文字,比每次完整新建更省对象。

用 geometry 字段画偏移符号

geometry 参数可以指向要素上的另一个几何属性。 这样同一个要素能在两个位置各画一个符号,而不用建两个要素:

var lonLat = ol.proj.fromLonLat([116.391263, 39.907359]);

var f = new ol.Feature({
  geometry: new ol.geom.Point(lonLat),
  /* 标注点向南偏 300 米,与主几何分开 */
  labelPoint: new ol.geom.Point([lonLat[0], lonLat[1] - 300]),
  name: '天安门'
});

f.setStyle([
  new ol.style.Style({
    image: new ol.style.Circle({ radius: 6 })
  }),
  new ol.style.Style({
    geometry: f.get('labelPoint'),
    text: new ol.style.Text({ text: f.get('name'), font: '12px sans-serif' })
  })
]);
引用本文

经纬志(2026)。《Style》。https://www.jingweizhi.com/openlayers/api/style.html(访问日期 2026-11-03)。