如何在没有样式函数的情况下动态设置Cluster层

时间:2015-10-21 05:52:22

标签: openlayers-3

如何在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;
}

1 个答案:

答案 0 :(得分:1)

当样式依赖于特征的某些属性(例如集群中的子特征数)时,

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);
相关问题