By now you should be getting pretty comfortable creating simple OpenLayers maps with a combination of raster and vector data. With raster data, there is no control over presentation, as the saying goes–what you see is what you get. Vector data, on the other hand, gives you direct control over presentation details. We've already alluded to vector styles, and used them in the previous chapter. Now, it is time to take full control of how we present our vector data!
In the last chapter, you saw how powerful the vector layer can be. In this chapter, we'll go a bit deeper and talk about how to customize the appearance of the features within a vector layer. We'll explore the following:
So, what is a vector style? Quite simply, it is a set of instructions about how to draw graphic primitives—the points, lines, polygons, and text that make up our vector features. OpenLayers provides a basic default style that renders features in various shades of blue. While this is quite nice, it's probably not what you'll want to use all the time.
You've already seen an example of a basic vector style in the previous chapter. Let's review it here:
var fill = new ol.style.Fill({
color: 'rgba(0,0,0,0.2)'
});
var stroke = new ol.style.Stroke({
color: 'rgba(0,0,0,0.4)'
});
var circle = new ol.style.Circle({
radius: 6,
fill: fill,
stroke: stroke
});
var vectorStyle = new ol.style.Style({
fill: fill,
stroke: stroke,
image: circle
});This code defines specific rules for the fill, stroke, and image properties of a new ol.style.Style object. The fill and stroke rules specify a color and opacity using the RGBA (Red, Green, Blue, and Alpha) format. The circle style is a special style that draws points as circles of a specific radius with a fill and stroke property. Together, these form a style object that OpenLayers uses to determine how to draw a feature. The fill property is used for filling polygons and circles. The stroke property is used to draw the outline of polygons, lines, and circles. The image property is used for drawing points. There is also a text property that we haven't seen yet.
The vector layer's style property accepts three different ways of specifying styles:
ol.style.Styleol.style.Style instancesWe'll look at style functions in more detail in the second half of this chapter, but briefly, a style function is one that returns an array of style objects to be used for a specific feature and resolution. In combination with feature properties, a style function allows for the implementation of advanced custom styling. Before we can run, we'd better learn how to walk.