[WFS]
Here I made an example for you, to show you how you can do the simple modifications that you mention.
In the example below, instead of modifying the layer style I modify the features style, it the same thing I just found simple to exemplify. So, in order to work in your case you just need to obtain the layer style and made the changes in the same way as the example.
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.1.1/css/ol.css" type="text/css">
<style>
.map {
height: 400px;
width: 100%;
}
</style>
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.1.1/build/ol.js"></script>
<title>Simple Style Change</title>
</head>
<body>
<div id="map" class="map"></div>
<script type="text/javascript">
// base style default of features
// features
const radius = 20000;
const cx = -80;
const cy = 35;
const fonts = [
'1.2em "Fira Sans", sans-serif',
'italic 1.2em "Fira Sans", serif',
'italic small-caps bold 16px/2 cursive',
'small-caps bold 24px/1 sans-serif',
'caption'
];
const baseStyle = new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'rgba(0, 0, 0, 1)',
width: 1
}),
fill: new ol.style.Fill({
color: 'rgba(0, 0, 0, 0.1)'
}),
text: new ol.style.Text({
stroke: new ol.style.Stroke({color: '#ffffff', width: 3})
})
});
// map
const view = new ol.View({
center: ol.proj.fromLonLat([cx-6, cy]),
zoom: 7
});
const vlayer = new ol.layer.Vector({
source: new ol.source.Vector(),
style: baseStyle
});
const map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
vlayer
],
view
});
// add features
const features = [];
let feat, style, fill, text;
for (let i = 0; i < 20; i++) {
feat = new ol.Feature({
geometry: ol.geom.Polygon.circular([cx-i, cy], radius)
.transform('EPSG:4326', 'EPSG:3857')
});
style = vlayer.getStyle().clone();
fill = vlayer.getStyle().getFill().clone();
fill.setColor(`rgba(${i*12},${i*12},${i*12},0.5)`)
style.setFill(fill);
text = vlayer.getStyle().getText().clone();
text.setFont(fonts[i % fonts.length]);
text.setText(`${i}`);
style.setText(text);
feat.setStyle(style);
features.push(feat);
}
vlayer.getSource().addFeatures(features);
</script>
</body>
</html>
UPDATE for WMS
For WMS you can use two parameter to dynamically change the style on request.
- styles: comma-separated value of the style names to applied, default style is apply on empty value. In this case, you have to define a set of styles with the simple changes you want and then you use the names of these style with the layers in OL.
- sld_body: the SLD XML text you want to apply to the map. In this case you have a base SLD and you modify it with JavaScript and use it with the layers in OL.
On OL you can specify this parameters, assuming that you are using TileWMS
, on creation with option parameter params
or with the method updateParams
.
GeoServer - WMS
OL API - TileWMS