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

Changing layer opacity

When you are working with many layers, both raster and vector layers, you will probably find situations where a layer that is on top of another layer obscures the one below it. This is more common when working with raster WMS layers without the transparent property set to true or tiled layers, such as OpenStreetMaps, and Bing Maps.

In this recipe, we'll create a slider that updates the layer opacity of the topmost layer, revealing a layer underneath as the opacity is lowered. The source code can be found in ch02/ch02-layer-opacity/. Here's a screenshot showing the layer opacity at 60%:

Changing layer opacity

How to do it…

We used jQuery UI to create the slider widget. Here are the steps to create this recipe:

  1. Create an HTML file adding the required OpenLayers dependencies, as well as jQuery UI and dependencies. In particular, here's the markup for the map and opacity panels:
    <div id="js-map" class="map"></div>
    <div class="pane">
      <h1>Layer opacity</h1>
      <p id="js-opacity">100%</p>
      <div id="js-slider"></div>
    </div>
  2. Next, create a map instance with the Stamen watercolor tile layer and the landscape WMS layer from Andy Allan:
    var map = new ol.Map({
      view: new ol.View({
        zoom: 8,
        center: [860000, 5558000]
      }),
      target: 'js-map',
      layers: [
        new ol.layer.Tile({
          source: new ol.source.Stamen({
            layer: 'watercolor'
          })
        }),
        new ol.layer.Tile({
          source: new ol.source.OSM({
            attributions: [
              new ol.Attribution({
                html: 'Tiles courtesy of ' +
                '<a href="http://www.thunderforest.com">' +
                'Andy Allan</a>'
              }),
              ol.source.OSM.ATTRIBUTION
            ],
            url: 'http://{a-c}.tile.thunderforest.com/' +
                 'landscape/{z}/{x}/{y}.png'
          })
        })
      ]
    }); 
  3. Cache the DOM element that reflects the opacity percentage:
    var $opacity = $('#js-opacity');
  4. Finally, create the jQuery UI slider widget and update the layer opacity and percentage display on the slide:
    $('#js-slider').slider({
      min: 0,
      max: 100,
      value: 100,
      slide: function(event, ui) {
        $opacity.text(ui.value + '%');
        map.getLayers().item(1).setOpacity(ui.value / 100);
      }
    });

How it works…

For the purpose of this recipe, let's focus in on the instantiation of the jQuery UI slider and how the map layer opacity is subsequently updated:

$('#js-slider').slider({
  min: 0,
  max: 100,
  value: 100,

Using jQuery, we target the DOM element that we want to convert into the slider widget. On the returned jQuery object, we attach the jQuery UI slider method with some configuration properties, which will create the slider widget as desired. The properties set an initial value of 100 to match the initial state of the map layer opacity, as well as a min and max value.

slide: function(event, ui) {
  $opacity.text(ui.value + '%');
  map.getLayers().item(1).setOpacity(ui.value / 100);
}

The slide property enables us to attach an event handler, which is called whenever the slider position updates. When this event fires, we have access to the event object and also the ui object from the jQuery UI. The ui object contains the new value from the slide action, and we update the text value of the DOM element to inform the user of the new opacity percentage.

We then fetch all the layers from the map using the map getLayers method, returning an ol.Collection object. This object provides us with some useful methods, such as item, which takes the index of an array item. We use this to get the second layer of the map.

The item method returns the second layer from the collection. This layer (an instance of ol.layer.Base), also contains many methods, one of which is setOpacity. We take the latest slider value (between 0 and 100) and convert it into the expected format for the setOpacity method (it must be between 0 and 1). This is achieved by dividing the value from the slider by 100. If the slider value is 60%, then 60 / 100 = 0.6. This change takes immediate effect, and you'll see the layer transparency update accordingly.

Layer opacity changes will fire an event called change:opacity. This is one of many layer events that you can subscribe to.

See also

  • The Changing the zoom effect recipe
  • The Adding WMS layer recipe
  • The Buffering the layer data to improve map navigation recipe