Is there a way to change the style (e.g. color) of a vector layer on button click?
I have defined a vector layer like this:
new OpenLayers.Layer.Vector("WFS", {
style: myStyle,
strategies: [new OpenLayers.Strategy.BBOX()],
protocol: new OpenLayers.Protocol.WFS({
url: "http://demo.opengeo.org/geoserver/wfs",
featureType: "tasmania_roads",
featureNS: "http://www.openplans.org/topp"
})
});
Now I want when I press a button (which runs a function) to change the style with a new style which I define as:
var newStyle = {
fill: true,
fillColor: "#ff0000"
};
Is something like this possible? I think I can not do this using redraw() or refresh() right?
One solution would be what I read here. (destroy the whole vector layer and build it again with the new style). But this doesn't seem very efficient either or?
EDITED
I tried this but doesn't seem to work. Instead I get all feature black:
// ADD STYLING - DIFFERENT COLORS
var styleContext = {
getColor: function (feature) {
var objectKeys = Object.keys(gidsAll); // use objectkeys to loop over all the object properties //use it to get the length
for (var i = 0; i < objectKeys.length; i++){
if (Math.round(feature.attributes.__gid) === parseInt(gidsAll[objectKeys[i]], 10)) {
return "green";
}
}
return "red"; //no images on this line
}
};
// define Style
var defaultStyle = new OpenLayers.Style({
fillColor: "${getColor}",
fillOpacity:"1",
strokeColor: "${getColor}",
strokeOpacity: "1",
strokeWidth: 8,
cursor: "pointer",
pointRadius: 8
}, {
context: styleContext
});
// Define style when selecting the feature
var selectStyle = new OpenLayers.Style({
'pointRadius': 8,
strokeColor: "cyan",
});
// Define the stylemap (loaded in each feature)
var featurestyleMap = new OpenLayers.StyleMap({
'default': defaultStyle,
'select': selectStyle
});
wfs_layer_network.style = featurestyleMap;
//then redraw the layer
wfs_layer_network.redraw();