【发布时间】:2015-10-24 20:02:36
【问题描述】:
所以在我的 Openlayers 3 中,我设置了一个默认样式,它会在图层第一次加载时呈现特征
function styleFunction(feature, resolution) {
var color = feature.get('color');
var name = feature.get('name');
var fill = new ol.style.Fill({
color: color
});
var stroke = new ol.style.Stroke({
color: "black",
lineCap: "butt",
lineJoin: "bevel",
width:1
});
var text= new ol.style.Text({
font: '20px Verdana',
text: name,
fill: new ol.style.Fill({
color: [64, 64, 64, 0.5]
})
})
var cStyle = new ol.style.Style({
fill: fill,
stroke: stroke,
text: text
});
return [cStyle];
}
当点击一个功能时,我希望该功能更改其样式,其余部分保持上面的默认样式。
这是我的尝试
//add simple click interaction to the map
var select = new ol.interaction.Select();
map.addInteraction(select);
//for every clicked feature
select.on('select', function(e) {
var name = e.selected[0].get('name');
//set the clicked style
var fillClick= new ol.style.Fill({
color: "black"
});
var strokeClick = new ol.style.Stroke({
color: "white",
lineCap: "butt",
lineJoin: "bevel",
width:3
});
var textClick= new ol.style.Text({
font: '10px Verdana',
text: name,
fill: new ol.style.Fill({
color: [64, 64, 64, 1]
})
})
var styleClick = new ol.style.Style({
stroke: strokeClick,
fill : fillClick,
text : textClick
});
//set all to default
for (i in e.selected){
e.selected[i].setStyle(styleFunction);
}
//reset the first selected to the clicked style
e.selected[0].setStyle(styleClick);
我在控制台上没有收到任何错误,但这不起作用。当我单击另一个时,单击的功能不会返回到默认样式。所有点击的功能都保留styleClick。
那么,我该如何解决这个问题,还有,有没有更简单的方法来做到这一点?我认为这种功能需要很多代码
谢谢
编辑
我换了
for (i in e.selected){
e.selected[i].setStyle(styleFunction);
}
与
var allfe = sourceVector.getFeatures();
for (i in allfe){
allfe[i].setStyle(styleFunction);
}
所以现在所有功能都将获得styleFunction 函数中定义的样式。
这不起作用。我得到Uncaught TypeError: feature.get is not a function 指的是函数的第一行,var color = feature.get('color'); 这个。
我不能只设置一个样式,我需要它是一个函数,这样我以后可以检查几何类型。
所以我的两个问题,
我不知道如何调试和修复这个错误
如果我有 500 个特征,每次点击都重绘所有特征,会减慢渲染速度。有没有其他解决方案?
谢谢
【问题讨论】:
-
嘿,@slevin,结果如何?
标签: openlayers-3