Book Image

OpenLayers 3.x Cookbook - Second Edition

By : Peter J. Langley, Antonio Santiago Perez
Book Image

OpenLayers 3.x Cookbook - Second Edition

By: Peter J. Langley, Antonio Santiago Perez

Overview of this book

OpenLayers 3 is one of the most important and complete open source JavaScript mapping libraries today. Throughout this book, you will go through recipes that expose various features of OpenLayers 3, allowing you to gain an insight into building complex GIS web applications. You will get to grips with the basics of creating a map with common functionality and quickly advance to more complicated solutions that address modern challenges. You will explore into maps, raster and vector layers, and styling in depth. This book also includes problem solving and how-to recipes for the most common and important tasks.
Table of Contents (14 chapters)
OpenLayers 3.x Cookbook Second Edition
Credits
About the Authors
About the Reviewer
www.PacktPub.com
Preface
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:

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