如何将集群层的样式定义为ol.style.Style
对象,而不是作为Openlayers 3中的函数?
我正在使用一个库(ol3-google-maps),它只接受ol.style.Style
对象进行样式化。官方的集群示例使用一个样式函数来动态地将每个集群的特征数量添加到它的图标上:
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样式函数在样式依赖于特征的某些属性(如集群中子特征的数量)时非常好。没有其他方法可以在样式中使用动态属性。
你可以为集群层使用一种不依赖于集群大小的通用样式(不显示特征的数量),比如这个例子。
但是,您也可以为每个特征设置非动态样式,而不是每个图层。样式可以根据它的属性来计算,给你一些样式函数的可能性。
这个示例是对官方示例的修改,没有使用普通样式函数。相反,它监听集群源的addfeature
和changefeature
事件,并根据它的属性为特性本身设置样式(参见下面的代码)。
并不是说这不是一个通用的解决方案或样式函数的替代品,尽管它应该可以很好地用于集群源。值得注意的是,您失去了基于分辨率生成样式的可能性。如果某个特征被其他图层使用,那么设置该特征的样式可能不可取。您还必须考虑性能问题。
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);