Table of Contents for
OpenLayers 3.x Cookbook - Second Edition

Version ebook / Retour

Cover image for bash Cookbook, 2nd Edition OpenLayers 3.x Cookbook - Second Edition by Antonio Santiago Perez Published by Packt Publishing, 2016
  1. Cover
  2. Table of Contents
  3. OpenLayers 3.x Cookbook Second Edition
  4. OpenLayers 3.x Cookbook Second Edition
  5. Credits
  6. About the Authors
  7. About the Reviewer
  8. www.PacktPub.com
  9. Preface
  10. What you need for this book
  11. Who this book is for
  12. Sections
  13. Conventions
  14. Reader feedback
  15. Customer support
  16. 1. Web Mapping Basics
  17. Creating a simple fullscreen map
  18. Playing with the map's options
  19. Managing the map's stack layers
  20. Managing the map's controls
  21. Moving around the map view
  22. Restricting the map's extent
  23. 2. Adding Raster Layers
  24. Using Bing imagery
  25. Using OpenStreetMap imagery
  26. Adding WMS layers
  27. Changing the zoom effect
  28. Changing layer opacity
  29. Buffering the layer data to improve map navigation
  30. Creating an image layer
  31. Setting the tile size in WMS layers
  32. 3. Working with Vector Layers
  33. Adding a GML layer
  34. Adding a KML layer
  35. Creating features programmatically
  36. Exporting features as GeoJSON
  37. Reading and creating features from a WKT
  38. Using point features as markers
  39. Removing or cloning features using overlays
  40. Zooming to the extent of a layer
  41. Adding text labels to geometry points
  42. Adding features from a WFS server
  43. Using the cluster strategy
  44. Reading features directly using AJAX
  45. Creating a heat map
  46. 4. Working with Events
  47. Creating a side-by-side map comparator
  48. Implementing a work-in-progress indicator for map layers
  49. Listening for the vector layer features' events
  50. Listening for mouse or touch events
  51. Using the keyboard to pan or zoom
  52. 5. Adding Controls
  53. Adding and removing controls
  54. Working with geolocation
  55. Placing controls outside the map
  56. Drawing features across multiple vector layers
  57. Modifying features
  58. Measuring distances and areas
  59. Getting feature information from a data source
  60. Getting information from a WMS server
  61. 6. Styling Features
  62. Styling layers
  63. Styling features based on geometry type
  64. Styling based on feature attributes
  65. Styling interaction render intents
  66. Styling clustered features
  67. 7. Beyond the Basics
  68. Working with projections
  69. Creating a custom control
  70. Selecting features by dragging out a selection area
  71. Transitioning between weather forecast imagery
  72. Using the custom OpenLayers library build
  73. Drawing in freehand mode
  74. Modifying layer appearance
  75. Adding features to the vector layer by dragging and dropping them
  76. Making use of map permalinks
  77. Index

Styling clustered features

When working with lots of feature points, it is common to use the cluster strategy to avoid the overlapping of points and improve the rendering performance. We've previously covered the clustering strategy in detail in the Using the cluster strategy recipe in Chapter 3, Working with Vector Layers, and although we introduced some custom styling in that recipe, we'll look at some more styling options to enhance the appearance of the clusters in this recipe.

We are going to load two separate GeoJSON files containing around 100 point geometries, each within a concentrated area, displaying the benefits of what a clustering strategy provides to this type of data. We will render these two sets of features on different layers, each layer with a unique style.

As an added extra, for one of the vector layers, we are going to include an icon of an arrow that points to a cluster with a high amount of points beneath it. You can see what we mean by viewing the following screenshot.

The source code can be found in ch06/ch06-styling-clustered-features, and here's what it'll look like (as you can see, clustering can be completely transformed into a style that best matches your application):

Styling clustered features

How to do it…

In order to create uniquely-styled clustering that can complement your own particular map application, follow these steps:

  1. Create an HTML file with OpenLayers dependencies and a div element to hold the map.
  2. Within a custom JavaScript file, instantiate an instance of ol.Map:
    var map = new ol.Map({
      view: new ol.View({
        zoom: 5, center: [13565432, -577252]
      }),
      target: 'js-map',
      layers: [
        new ol.layer.Tile({
          source: new ol.source.Stamen({layer: 'watercolor'})
        })
      ]
    });
  3. Create the first vector layer style function, as follows:
    var style1 = function(feature) {
      var length = feature.get('features').length;
      var styles = [
        new ol.style.Style({
          image: new ol.style.RegularShape({
            radius: 20, points: 4,
            stroke: new ol.style.Stroke({
              color: [1, 115, 54, 0.9], width: 2
            }),
            fill: new ol.style.Fill({
              color: [255, 255, 255, 0.3]
            })
          }),
          text: new ol.style.Text({
            text: length.toString(), rotation: -0.3,
            font: '12px "Helvetica Neue", Arial',
            fill: new ol.style.Fill({
              color: [1, 115, 54, 1]
            }),
            stroke: new ol.style.Stroke({
              color: [255, 255, 255, 1], width: 2
            })       
          })
        })
      ];
      if (length > 15) {
        styles.push(new ol.style.Style({
          image: new ol.style.Icon({
            src: '../../assets/images/arrow-left.png',
            rotation: -0.3, scale: 1.2,
            anchor: [-0.2, 0.5]
          })
        }))
      }
      return styles;
    };
  4. Create the second vector layer style function:
    var style2 = function(feature) {
      var length = feature.get('features').length;
      return [
        new ol.style.Style({
          image: new ol.style.RegularShape({
            radius: 20, points: 3,
            stroke: new ol.style.Stroke({
              color: [255, 188, 17, 0.9], width: 2
            }),
            fill: new ol.style.Fill({
              color: [173, 10, 43, 0.7]
            })
          }),
          text: new ol.style.Text({
            text: length.toString(), offsetY: 9,
            font: '12px "Arial Black"',
            fill: new ol.style.Fill({
              color: 'white'
            }),
            stroke: new ol.style.Stroke({
              color: [0, 0, 0, 1], width: 3
            })   
          })
        })
      ];
    };
  5. Set up a method that can instantiate a new clustered vector layer:
    var createClusteredLayer = function(url, style) {
      return new ol.layer.Vector({
        source: new ol.source.Cluster({
          distance: 25, projection: 'EPSG:3857',
          source: new ol.source.Vector({
            url: url,
            format: new ol.format.GeoJSON({
              defaultDataProjection: 'EPSG:3857'
            })
          })
        }),
        style: style
      })
    };
  6. Finally, add two clustered vector layers with different source URLs and styling functions:
    map.addLayer(createClusteredLayer('points1.geojson', style1));
    map.addLayer(createClusteredLayer('points2.geojson', style2));

How it works…

Much of the code here should look familiar to the earlier recipes in this chapter. Let's take a closer look at some of the newly utilized properties and custom JavaScript that is implemented in this recipe.

We will begin by breaking down what the style1 function does of type ol.style.StyleFunction (a method of styling we saw earlier in the Styling based on feature attributes recipe):

var style1 = function(feature) {
  var length = feature.get('features').length;
  var styles = [
    new ol.style.Style({
      image: new ol.style.RegularShape({
        radius: 20, points: 4,
        stroke: new ol.style.Stroke({
          color: [1, 115, 54, 0.9], width: 2
        }),

We store a reference of the feature length (cluster count) in a variable, namely length. This is what gets used for the text label.

We create a new instance of ol.style.Style and assign a customized ol.style.RegularShape instance to the image property. We used this type of styling in order to create a star geometry for the Styling features based on geometry type recipe. However, this time we use it to create a square geometry (points is assigned as 4—the number of polygon sides).

text: new ol.style.Text({
  text: length.toString(), rotation: -0.3,

This snippet is also plucked from the style1 function. We can see that when we instantiate a new instance of ol.style.Text (for the cluster label), we use the count from the length variable, being sure to convert it to type string, as well as setting the text rotation to something nondefault, via the rotation property. The value is in radians, and produces a slanting effect.

if (length > 15) {
    styles.push(new ol.style.Style({
      image: new ol.style.Icon({
        src: '../../assets/images/arrow-left.png',
        rotation: -0.3, scale: 1.2,
        anchor: [-0.2, 0.5]
      })
    }))
  }

The last major part of the style1 function is the preceding conditional check on the feature count for the cluster.

If the number of features within the cluster is greater than 15, then we push another instance of ol.style.Style in the array before returning the completed styles array. We instantiate an instance of ol.style.Icon to provide this cluster feature with an icon of an arrow. Just like the text label, we rotate the icon by 0.3 radians, and we also scale up the icon by 20% of its original size (1.2).

The anchor property contains the x,y anchor points for the icon using fraction units (you can adjust it to use pixel units via the anchorXUnits or anchorYUnits properties). The default uses the fraction units of [0.5, 0.5]. We modified this so that the arrow is offset over to the right of the cluster's center, with -0.2 instead of 0.5.

Let's move on to take a look at the style2 function by extracting just a few portions of the method for discussion:

image: new ol.style.RegularShape({
  radius: 20, points: 3,

Again, we've used an instance of ol.style.RegularShape to customize the geometry that is used for the cluster feature. With the points property assigned a value of 3 sides, it produces a triangle.

text: new ol.style.Text({
  text: length.toString(), offsetY: 9,
  font: '12px "Arial Black"', 

This snippet is the last snippet of the style2 function that we'll look over. It creates an instance of the text style constructor. The newly-introduced property is offsetY, which is used to vertically align the text label (cluster feature count) towards the bottom of the triangle. The typography used is a thicker style of font (Arial Black).

var createClusteredLayer = function(url, style) {
  return new ol.layer.Vector({
    source: new ol.source.Cluster({
      distance: 25, projection: 'EPSG:3857',
      source: new ol.source.Vector({
        url: url
        format: new ol.format.GeoJSON({
          defaultDataProjection: 'EPSG:3857'
        })
      })
    }),
    style: style
  })
};

We created a function to return a customized instance of a vector layer. The function accepts the parameters of url for the source URL, and style for the style function to be used by the layer.

We specified the projection as EPSG:3857 on the cluster instance (ol.source.Cluster) via the projection property, and we have also been explicit about the projection when formatting the GeoJSON via the defaultDataProjection property.

The style function is applied to the vector layer style property, which means that the layer styling rules will be applied to every feature within the layer.

See also

  • The Styling interaction render intents recipe
  • The Styling features based on geometry type recipe
  • The Using the cluster strategy recipe in Chapter 3, Working with Vector Layers