如何在没有样式功能的情况下动态设置集群层的样式

How to dynamically style Cluster layer without style function

如何在 Openlayers 3 中将簇层的样式定义为 ol.style.Style 对象,而不是函数?

我使用的库 (ol3-google-maps) 只接受 ol.style.Style 对象进行样式设置。 official cluster example 使用样式函数将每个集群中的特征数量动态添加到它的图标:

style: function(feature, resolution) {
  console.log(feature);
  var size = feature.get('features').length;
  var style = styleCache[size];
  if (!style) {
    style = [
      new ol.style.Style({
        image: new ol.style.Circle({
          radius: 10,
          stroke: new ol.style.Stroke({
            color: '#fff'
          }),
          fill: new ol.style.Fill({
            color: '#3399CC'
          })
        }),
        text: new ol.style.Text({
          text: size.toString(),
          fill: new ol.style.Fill({
            color: '#fff'
          })
        })
      })
    ];
    styleCache[size] = style;
  }
  return style;
}

ol3 样式函数在样式取决于某些 属性 特征时非常有用,例如集群中子特征的数量。没有其他方法可以在样式中使用动态属性。

您可以为不依赖于簇大小(不显示特征数量)的簇层使用通用样式,例如 this example.

但是,您也可以为每个要素设置非动态样式,而不是为每个图层。该样式可以根据其属性进行计算,为您提供样式函数的一些可能性。

This example是对官方例子的修改,没有使用普通样式的函数。相反,它会侦听集群源的 addfeaturechangefeature 事件,并根据其属性将样式设置为特征本身(参见下面的代码)。

并不是说这不是样式函数的通用解决方案或替代品,尽管它应该适用于集群源。值得注意的是,您失去了根据分辨率生成样式的可能性。如果其他图层使用该功能,则可能不需要为该功能设置样式。您还必须考虑性能问题。

var styleCache = {};
var styleFunctionIsChangingFeature = false
var styleFunction = function (evt) {
    if (styleFunctionIsChangingFeature) {
        return;
    }
    var feature = evt.feature;
    var size = feature.get('features').length;
    var style = styleCache[size];
    if (!style) {
        style = new ol.style.Style({
            image: new ol.style.Circle({
                radius: 10,
                stroke: new ol.style.Stroke({
                    color: '#fff'
                }),
                fill: new ol.style.Fill({
                    color: '#3399CC'
                })
            }),
            text: new ol.style.Text({
                text: size.toString(),
                fill: new ol.style.Fill({
                    color: '#fff'
                })
            })
        });
        styleCache[size] = style;
    }
    styleFunctionIsChangingFeature = true
    feature.setStyle(style);
    styleFunctionIsChangingFeature = false
};

clusterSource.on('addfeature', styleFunction);
clusterSource.on('changefeature', styleFunction);