- Mastering OpenLayers 3
- Gábor Farkas
- 410字
- 2025-04-04 20:18:52
Styling vector layers
You might or you might not be familiar with vector styling at this point. If you know about the concept, however, a little revision won't hurt. In this example, we will change the default vector style of the example dataset to green stars. As vector data is drawn directly to the canvas by the library, their styles can be changed only by inner methods with a limited set of values.
You can see a js
file named ch02_vector
in the code appendix. You can use this file with the previous example or extend the original one with the following rules:
var vectorLayer = new ol.layer.Vector({ source: new ol.source.Vector({ format: new ol.format.GeoJSON({ defaultDataProjection: 'EPSG:4326' }), url: '../../res/world_capitals.geojson', attributions: [ new ol.Attribution({ html: 'World Capitals © Natural Earth' }) ] }), style: new ol.style.Style({ image: new ol.style.RegularShape({ stroke: new ol.style.Stroke({ width: 2, color: [6, 125, 34, 1] }), fill: new ol.style.Fill({ color: [25, 235, 75, 0.3] }), points: 5, radius1: 5, radius2: 8, rotation: Math.PI }) }) });
In this simple style object, we define only a point symbolizer. It is a regular shape, which can be a simple, regular polygon. The polygon can be convex if it has only one radius value, and concave if it has two. Our star has five points and an outer radius of 8
pixels. The colors of its stroke, and fill, are expressed in RGBA values, which can be done by passing an array to their color
parameter with four values. As the star will be upside down by default, we rotate it by 180 degrees The library only accepts radian values; thus, we have to rotate the star by π.
Tip
Using RGBA values is the only way to express opacity in vector styling. For regular styling with CSS, it is also a good practice as it takes fewer lines and all the major browsers support it.
Save the updated code, link it to the previous example, and open it up in your favorite browser. You should see the capitals represented by green stars:

Tip
We have only defined a symbolizer for point geometries in our style object. This means that the line and polygon symbolizers are set to null. If you use this style object on line, or polygon features, they would simply not render. To make general style objects for multiple geometry types, you have to provide at least a stroke
style and a fill
style besides image
.