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

Using the cluster strategy

Imagine a scenario where we want to show all the gas stations in every city around the world. What will happen when the user navigates within the map and sets a zoom level to look at the whole world? We're presented with an overwhelming dominance of points, overlapping each other all at the same place, providing little visual value to the user.

A solution to this problem is to cluster the features on each zoom level. OpenLayers makes this very easy to implement.

This recipe (source code in ch03/ch03-clustering) shows how easy it is to apply clustering on a vector layer, which is responsible for grouping the features to avoid a situation similar to the one discussed earlier that can be seen in the following screenshot:

Using the cluster strategy

How to do it…

Utilize the great clustering capability of OpenLayers using the following instructions:

  1. Create an HTML file with OpenLayers dependencies and a div element to hold the map.
  2. Initialize the map, as follows:
    var map = new ol.Map({
      view: new ol.View({
        zoom: 4,
        center: [2152466, 5850795]
      }),
      target: 'js-map',
      layers: [
        new ol.layer.Tile({
          source: new ol.source.MapQuest({layer: 'sat'})
        })
      ]
    });
  3. Randomly generate a bunch of points that are restricted to a particular extent:
    var getRandomInt = function(min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min;
    };
    
    var features = [];
    var numberOfFeatures = 0;
    
    while(numberOfFeatures < 100) {
      var point = new ol.geom.Point([
        getRandomInt(1545862, 2568284),
        getRandomInt(6102732, 7154505)
      ]);
    
      features.push(new ol.Feature(point));
      numberOfFeatures++;
    }
  4. Set up the styling function used to render the clusters:
    var getStyle = function(feature) {
      var length = feature.get('features').length;
      return [
        new ol.style.Style({
          image: new ol.style.Circle({
            radius: Math.min(
              Math.max(length * 1.2, 15), 20
            ),
            fill: new ol.style.Fill({
              color: [0, 204, 0, 0.6]
            })
          }),
          text: new ol.style.Text({
            text: length.toString(),
            fill: new ol.style.Fill({
              color: 'white'
            }),
            stroke: new ol.style.Stroke({
              color: [0, 51, 0, 1],
              width: 1
            }),
            font: '10px "Helvetica Neue", Arial'
          })
        })
      ];
    };
  5. Create the vector layer, add the cluster source, then add the layer to the map:
    var vectorLayer = new ol.layer.Vector({
      source: new ol.source.Cluster({
        distance: 25,
        source: new ol.source.Vector({
          features: features
        })
      }),
      style: getStyle
    });
    map.addLayer(vectorLayer);

How it works…

We randomly placed 100 geometry points within an arbitrary extent across Europe. We previously used this technique in the Exporting features as GeoJSON recipe, where we explained in detail how this works. If you need a reminder, head over to that recipe, as we'll move on and focus our attention on how the clustering is achieved.

Our getStyle method is called by OpenLayers when the cluster needs rendering. It's attached to the style property of the vector layer. We want to add a text label to display the number of points beneath the cluster and give the cluster some nondefault styling. We saw very similar styling with accompanying explanations in the Adding text label to geometry point recipe, so we will only take a look over some parts of the styling used for this recipe:

image: new ol.style.Circle({
  radius: Math.min(
    Math.max(length * 1.2, 15), 20
  ),

Circles will be drawn on the map to represent clusters of points. The more points a cluster contains, the larger the radius of the circle will be. Features that are part of a clustered source are applied a custom property, namely features. This contains an array of all the features within that cluster. We retrieve this value using the ol.Feature get method, feature.get('features').length, and store it in a variable, namely length.

We multiply the length of the features by 1.2, but we pick the maximum number of either the result of the multiplication or 15 using the JavaScript Math.max method. We don't want any clusters smaller than a radius of 15.

On the contrary, we don't want any cluster bigger than a radius of 20, so Math.min is used to wrap the result of the maximum radius and limit the radius if required.

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

The text of the cluster is simply derived from the number of features within the cluster array. The number must be converted to a string type for OpenLayers. The toString method is a native JavaScript method for type coercion.

The rest of the ol.style.Style object simply assigns colors, widths, and fonts wherever applicable.

var vectorLayer = new ol.layer.Vector({
  source: new ol.source.Cluster({
    distance: 25,
    source: new ol.source.Vector({
      features: features
    })

We create a vector layer as normal, but source is an instance of ol.source.Cluster (which extends the ol.source.Vector class).

The distance property of the cluster source enforces the minimum distance (in pixels) between clusters. The default is 20.

The source property of the cluster source is an instance of ol.source.Vector, where we pass in the 100 generated features from earlier.

Every time the zoom level changes, the cluster strategy computes the distance among all features and adds all the features that conform to some parameters of the same cluster.

See also

  • The Creating features programmatically recipe
  • The Adding features from a WFS server recipe