In this example, we'll use the country data again and draw each polygon with two styles to create a shadow effect around the continents.
countryStyle to provide a somewhat darker stroke:var countryStyle = new ol.style.Style({
fill: new ol.style.Fill({
color: [203, 194, 185, 1]
}),
stroke: new ol.style.Stroke({
color: [101, 95, 90, 1],
width: 1
}),
zIndex: 2
});var shadowStyle = new ol.style.Style({
stroke: new ol.style.Stroke({
color: [0, 0, 127, 0.15],
width: 8
}),
zIndex: 1
});var countries = new ol.layer.Vector({
source: new ol.source.GeoJSON({
projection: 'EPSG:3857',
url: '../assets/data/countries.geojson'
}),
style: [shadowStyle, countryStyle]
});
By combining two styles, we achieved the desired effect. In the first step, we modified our starting style slightly to sharpen the country outline—this makes them easier to see over the shadows. In the second step, we added another style for the country layer with a wide, mostly transparent stroke and no fill. Lastly, we provided an array as the style property for our countries layer.
There is one thing you really need to be aware of when using arrays of styles—each feature is drawn once for each style. This can have dramatic performance implications when dealing with a lot of features. If you create a style array with two styles, you are effectively doubling the number of features being rendered. This will have no visible effect on a small number of simple features, but will start to have a noticeable effect when rendering lots (say hundreds of thousands) of features, or a smaller number of highly complex features.
In practice, it doesn't really double the rendering time as their efficiencies are built into OpenLayers that try to avoid expensive operations as much as possible. For example, the same effect can be achieved using two vector layers. This will be more inefficient as OpenLayers has to process the geometries twice, while they only have to be processed once when using an array of styles.
If you have been paying attention, you will have noticed that we added a zIndex property to each style in the previous example. Try removing the zIndex from both the styles and observe the result. This should give you an appreciation of what the zIndex property does. Without it, OpenLayers renders the features one at a time with their complete style, which would mean that the shadow from one country will overlap an adjacent country rather than just forming a shadow around each continent.