Now that we've seen all the basic style properties and how to combine them as arrays of styles, it's time to learn how to use them in conjunction with feature properties to achieve dynamic styles. This is actually the last of our three ways of specifying the style property—the style function.
We said at the beginning of the chapter that a style function is one that returns an array of style objects to be used for a specific feature and zoom level.
What does this mean? It's really quite straightforward, but extremely powerful. A style function is nothing more than a JavaScript function that receives two parameters—the feature being styled, and the resolution of the map's view. It is required to return an array of ol.style.Style objects when it is called. For instance, we could have written our country style example using a style function like this:
var countryStyleFunction = function(feature, resolution) {
return [countryStyle]; // the basic style we already defined
};
var countries = new ol.layer.Vector({
source: countrySource,
style: countryStyleFunction
});This example doesn't use the feature or the resolution arguments, but does illustrate how simple the concept of a style function is. In fact, when you provide a style or an array of styles as the style property of a vector layer, OpenLayers creates a style function internally that looks exactly like this.
You might be wondering if it's this simple, then how can we claim that it's extremely powerful? The power really comes when you use the feature and the resolution to dynamically create styles.
At the end of the previous chapter, we introduced the concept of feature properties and the methods used to retrieve them. Now, we can make practical use of this knowledge by using properties to create styles on the fly.