openlayers-3

What's "an array of ol.style.Style" good for?


A style of an ol.layer.Vector can be set as ol.style.Style, a style function or an array of ol.style.Style. What's the array for and what does it do -- compared to just passing an ol.style.Style object?

I cannot find any information on this, neither in the official API docs nor in the tutorials.


Solution

  • Because I think this is still relevant and the edit queue is full for the approved answer, I'm posting this with the links updated and with code examples.

    The most common way to see the array of styles in action is when drawing features since this is default style in Openlayers. For the line to appear blue with a white border it has to have two styles since it can't be done with a single Style. Openlayers does this by default like this:

    styles['LineString'] = [
        new Style({
          stroke: new Stroke({
            color: white,
            width: width + 2,
          }),
        }),
        new Style({
          stroke: new Stroke({
            color: blue,
            width: width,
          }),
        }),
      ];
    

    source

    To expand on how usefull this feature could be you could check the custom polygons example. To have the vertices highlighted, they use two styles, one for the vertices and another for the polygon contour itself. Relevant piece of code:

    const styles = [
      new Style({
        stroke: new Stroke({
          color: 'blue',
          width: 3,
        }),
        fill: new Fill({
          color: 'rgba(0, 0, 255, 0.1)',
        }),
      }),
      new Style({
        image: new CircleStyle({
          radius: 5,
          fill: new Fill({
            color: 'orange',
          }),
        }),
        geometry: function (feature) {
          // return the coordinates of the first ring of the polygon
          const coordinates = feature.getGeometry().getCoordinates()[0];
          return new MultiPoint(coordinates);
        },
      }),
    ];