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

Managing the map's controls

OpenLayers comes with lots of controls to interact with the map, such as pan, zoom, show overview map, edit features, and so on.

In the same way as layers, the ol.Map class has methods to manage the controls that are attached to the map.

We're going to create a way to toggle map controls on or off. The source code can be found in ch01/ch01-map-controls/. Here's what we'll end up with:

Managing the map's controls

How to do it…

  1. Create a new HTML file and add the OpenLayers dependencies as well as the jQuery library. In particular, add the following markup to the body:
    <div id="js-map" class="map"></div>
    <div class="pane">
      <h1>Controls</h1>
      <ul id="js-controls">
        <li>
          <label>
            <input type="checkbox" checked value="zoomControl">
            <span>Zoom control</span>
          </label>
        </li>
        <li>
          <label>
            <input type="checkbox" checked value="attributionControl">
            <span>Attribution control</span>
          </label>
        </li>
        <li>
          <label>
            <input type="checkbox" checked value="rotateControl">
            <span>Rotate control</span>
          </label>
        </li>
      </ul>
    </div>
  2. Create a new CSS file and add the following:
    .map {
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 20%;
    }
    
    .pane {
      position: absolute;
      top: 0;
      bottom: 0;
      right: 0;
      width: 20%;
      background: ghostwhite;
      border-left: 5px solid lightsteelblue;
      box-sizing: border-box;
      padding: 0 20px;
    }
  3. Create a new script file and create the map, as follows:
    var map = new ol.Map({
      layers: [
        new ol.layer.Tile({
          source: new ol.source.MapQuest({
            layer: 'osm'
          })
        })
      ],
      view: new ol.View({
        center: [12930000, -78000],
        zoom: 3
      }),
      target: 'js-map',
      controls: []
    });
  4. Create some controls and add them to the map, as follows:
    var zoomControl = new ol.control.Zoom({
      zoomInTipLabel: 'Zoom closer in',
      zoomOutTipLabel: 'Zoom further out',
  
      className: 'ol-zoom custom-zoom-control'
    });
    
    var attributionControl = new ol.control.Attribution({
      collapsible: false,
      collapsed: false
    });
    
    var rotateControl = new ol.control.Rotate({
      autoHide: false
    });
    
    map.addControl(zoomControl);
    map.addControl(attributionControl);
    map.addControl(rotateControl);
  5. Finally, enable the control toggle logic:
    $('#js-controls').on('change', function(event) {
      var target = $(event.target);
      var control = target.val();
    
      if (target.prop('checked')) {
        map.addControl(window[control]);
      } else {
        map.removeControl(window[control]);
      }
    });

How it works…

Our HTML and CSS divide up the page so that it contains the map and a control panel. Within this panel are three checkboxes that correspond to the three controls that will be added to the map. Toggling the checkboxes will, in turn, add or remove the selected controls.

It's important to note that the value of the checkboxes match up with the variable names of the controls in the JavaScript. For example, value="zoomControl" will link to the map control variable named zoomControl.

Let's pick apart the OpenLayers code to find out how this works:

var map = new ol.Map({
  
// ...
  controls: []
});

This map instantiation code will be familiar from the previous recipes, but note that because we don't want OpenLayers to set any default controls on the map, we explicitly pass an empty array to the controls property.

var zoomControl = new ol.control.Zoom({
  zoomInTipLabel: 'Zoom closer in',
  zoomOutTipLabel: 'Zoom further out',
  className: 'ol-zoom custom-zoom-control'
});

We store a reference to the zoom control inside the zoomControl variable. We've decided to customize the tool tips that appear for the plus and minus buttons. The className property has also been modified to include both the default class name for the zoom control (ol-zoom) in order to inherit the default OpenLayers styling and a custom class of custom-zoom-control. We can use this custom class name as a CSS hook for any of our own styles that override the defaults.

var attributionControl = new ol.control.Attribution({
  collapsible: false,
  collapsed: false
});

We store a reference to the attribution control inside the attributionControl variable. This control normally allows the user to collapse the attribution, and it's initial state is collapsed by default. By specifying these two properties, we have inverted the defaults.

var rotateControl = new ol.control.Rotate({
  autoHide: false
});

We store a reference to the rotate control inside the rotateControl variable. Normally, this control is only displayed when the map rotation is anything other than 0. We explicitly set this control to not automatically hide itself.

map.addControl(zoomControl);
map.addControl(attributionControl);
map.addControl(rotateControl);

All three controls are added to the map instance.

$('#js-controls').on('change', function(event) {
  var target = $(event.target);
  var control = target.val();

  if (target.prop('checked')) {
    map.addControl(window[control]);
  } else {
    map.removeControl(window[control]);
  }
});

We take advantage of event bubbling in JavaScript and attach a single change event listener to the HTML containing the list of layers; this is more efficient than attaching an event listener to each input element.

When a checkbox is toggled, this event handler is executed. The event target (the checkbox) is cached inside the target variable as it's used more than once. The value of the checkbox (which is also the name of the map control) is stored inside the control variable.

The new state of the checkbox for this control is passed into the if statement. If this is enabled, we add the control to the map with the ol.Map method, addControl. Otherwise, we remove the control from the map with the opposite ol.Map method, removeControl.

We use the checkbox value to select the matching OpenLayers control from the window object using array notation. The control's variable name (for example, zoomControl) will be the same as the checkbox value (for example, zoomControl), which is how this link is forged.

Note

All controls are a subclass of ol.control.Control. This means that any controls extended off this class will inherit the ol.Object methods (such as get and set), as well as other functions, such as getMap, which informs you which map this control is attached to. The ol.control.Control class makes creating custom controls much easier—a recipe that's covered later on in this book.

See also

  • The Managing the map's stack layers recipe
  • The Moving around the map view recipe