2015-10-21 67 views
1

如何在Openlayers 3中将集群层的样式定义为ol.style.Style对象而不是函数?如何在没有样式函数的情况下动态设置集群层的样式

我正在使用仅接受ol.style.Style对象进行造型的库(ol3-google-maps)。该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; 
} 
+0

请澄清一下您的问题。你想要什么样的物体?你指的是什么图书馆? –

+0

Hi Alvin, 在上面的代码中,style属性从函数(特征,分辨率)中取值。我想直接创建ol.style.Style的一个对象,而不是使用该函数。 我正在使用mapgears库来将谷歌地图与ol3进行整合: - https://github.com/mapgears/ol3-google-maps 目前,图书馆没有将功能作为样式属性的值。 – user189107

+0

我不认为没有样式函数的集群目前可以在ol3中使用。不过,我很乐意听到更多关于此的信息。 –

回答

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); 
+0

Alvin,非常感谢您的回答。 – user189107

+0

Alvin,你能否删除我的疑问? 为什么style属性总是定义为一个数组,但不是直接定义为ol.style.Style对象? – user189107

+0

它并不总是一个数组。 'ol.Feature'和'ol.layer.Vector'的样式选项可以是一个单独的'ol.style.Style',这样的对象的数组或者返回这样一个数组的样式函数。设置静态样式时,一个样式的数组等同于设置没有数组的样式。当多个样式用于相同功能时,样式阵列很有用。我从答案中删除了数组。 –

相关问题