[GIS] Applying styles to WMS layer using OpenLayers

openlayers-2stylewms

I am working with OpenLayers (and GeoServer) and I am showing a WMS layer with countries in a map.
Each object (country) in the layer has an attribute called NAME (the name of the country).

I created a filter like the following in order to see only Italy (it's an example)

myFilter = new OpenLayers.Filter.Comparison({
    type: OpenLayers.Filter.Comparison.EQUAL_TO,
    matchCase: false, 
    property: 'NAME',
    value: 'Italy'
});

This work perfectly and if I apply it to the layer and call redraw() method I can see only one country.

Now I would like to do the same thing with sytles, in order to highlight Italy but keep visible all the other countries in the map.
I created a style like the one below, but now I don't know how I can apply this to the layer.

var style = new OpenLayers.Style();
var ruleLow = new OpenLayers.Rule({
    filter: myFilter,
    symbolizer: {fillColor: "green"}
});
style.addRules([ruleLow]);          

Can I apply the style to a WMS layer or only to a vector layer?

Best Answer

In general the approach you have outlined will only work with vector layers. WMS layers are pictures of the map sent to you by the WMS server so it is harder to change their style on the fly as you would like. You probably want to see if it is possible to make a WFS request for the highlighted polygon and overlay that over the WMS base layer.

There are ways to send an SLD file with the WMS request to ask the server to style the map in a way that suits you. However not all servers (or clients) support this as it is much less efficient (it prevents the server caching the result for other users for example). See this example if that is what you want to do.