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

Listening for mouse or touch events

So far, in this chapter, we've looked at how to respond to events that OpenLayers itself publishes, such as tile load events and vector feature events, such as feature added. However, what about user-driven gestures and interactions with the map? This recipe takes a look at some of these types of events.

We'll demonstrate the click or tap and map panning events. When the user clicks on or touches the map, the geometry and pixel coordinates will be displayed in the sidebar. When the map is panned, the new visible extent of the map will be displayed in the sidebar as well.

The source code can be found in ch04/ch04-mouse-touch-events, and here's a screenshot of what this will look like:

Listening for mouse or touch events

How to do it…

To set up and subscribe to some user-driven events, follow these steps:

  1. Create an HTML file and include the OpenLayers dependencies. In particular, include the div element for the map and the markup for the side panel and content:
    <div id="js-map" class="map"></div>
    <div class="pane">
      <h1>Mouse/touch events</h1>
      <div class="panel panel-default">
        <h3 class="panel-title">Event results</h3>
        <div class="panel-body">
          <p class="event-heading">Current map extent</p>
          <p>
            <code>[</code>
            <samp id ="js-extent">n/a</samp>
            <code>]</code>
          </p>
    
          <p class="event-heading">Coordinates at last click</p>
          <p>
            <code>[</code>
            <samp id="js-coords">n/a</samp>
            <code>]</code>
          </p>
    
          <p class="event-heading">Pixels at last click</p>
          <p>
            <code>[</code>
            <samp id="js-pixels">n/a</samp>
            <code>]</code>
          </p>
        </div>
      </div>
    </div>
  2. Cache some DOM elements to be used for display, as follows:
    var coords = document.getElementById('js-coords');
    var pixels = document.getElementById('js-pixels');
    var extent = document.getElementById('js-extent');
  3. Set up the map with a view and raster layer:
    new ol.Map({
      view: new ol.View({
        zoom: 10,
        center: [-9016970, 4437475]
      }),
      target: 'js-map',
      layers: [
        new ol.layer.Tile({source: new ol.source.Stamen(
          {layer: 'terrain'}
        )})
      ]
    })
  4. Subscribe to some map events and update the sidebar elements accordingly:
    .on(['click', 'moveend'], function(event) {
      if (event.type === 'click') {
        coords.innerHTML = event.coordinate.join(',<br>');
    
        var pixelsAtCoords =
          event.map.getPixelFromCoordinate(event.coordinate);
        pixels.innerHTML = [
          pixelsAtCoords[0].toFixed(0),
          pixelsAtCoords[1].toFixed(0)
        ].join(', ');
      } else {
        extent.innerHTML = event.map.getView().calculateExtent(
          event.map.getSize()
        ).join(',<br>');
      }
    });

How it works…

We've used the CSS framework Bootstrap to style the sidebar content. Some of the HTML has been omitted for brevity, so please view the book source code for the complete implementation.

Referring to the following code section, note that after we instantiate the map, we immediately chain the on method. The map instantiation returns the map instance (of ol.Map), which enables us to carry on without storing a reference to the map in another variable.

.on(['click', 'moveend'], function(event) {
  if (event.type === 'click') {
    coords.innerHTML = event.coordinate.join(',<br>');

    var pixelsAtCoords =
      event.map.getPixelFromCoordinate(event.coordinate);
    pixels.innerHTML = [
      pixelsAtCoords[0].toFixed(0),
      pixelsAtCoords[1].toFixed(0)
    ].join(', ');

We have supplied an array of events as the first parameter to the on method, namely the click and moveend events. Due to this combined event handler, we must differentiate between the event types when the handler is called, which is why we conditionally check the event.type property before performing the relevant logic.

The event object contains the coordinates of where the map was clicked or touched within event.coordinate. This is an array of x and y coordinates that we convert into a string, which is separated by a comma and an HTML break tag using the helpful JavaScript join method. This formats the coordinates as desired, which are then added to the DOM via the JavaScript innerHTML method.

As well as the geometry coordinates, we also want the pixel coordinates of the event. The event object stores a reference to the map (event.map), for which the map object has a method that'll return the pixel coordinates from the geometry coordinates, which is called getPixelFromCoordinate. This method expects an array of type ol.Coordinates, so we pass in the event coordinates (event.coordinate) and store the ol.Pixel type array into a variable, namely pixelsAtCoords.

Note

It's worth mentioning that the event object already provides the pixel coordinates within event.pixel. The pixel values are conveniently returned without any decimal places. In any case, this was a good learning exercise to expose another OpenLayers API method.

We finish by updating the DOM element that displays the pixel coordinates. To save manual string concatenation, we have built up a temporary array containing the pixel coordinates without any decimal places (using the toFixed JavaScript method). We also fused together the array items with a comma and space delimiter using the JavaScript join method once again.

} else {
    extent.innerHTML = event.map.getView().calculateExtent(
      event.map.getSize()
    ).join(',<br>');
  }

Within the same handler, if it's not a click event, then it must be a moveend event. This event is published when the user has finished panning the map. In order to retrieve the new extent of the visible map, we grab a reference for the view (event.map.getView) and utilize the calculateExtent view method. This method expects the size, in pixels, of the area of interest. For us, this is the whole map in sight, which is retained from the map method, getSize.

The returned extent array is converted into a string, delimited by a comma and HTML break element, and added to the applicable DOM element for display.

There's more…

There are plenty more map events that are up for grabs, such as the self-explanatory events pointerdrag and pointermove. To capture double-clicks or taps, you can use dblclick, and there are also events for when the map's view is changed (change:view) and when the map's size changes (change:size). This is useful for responsive design techniques.

I recommend that you take a look at the OpenLayers documentation in your own time to familiarize yourself with what's on offer.

See also

  • The Creating features programmatically recipe in Chapter 3, Working with Vector Layers
  • The Zooming to extent of layer recipe in Chapter 3, Working with Vector Layers
  • The Creating a side-by-side map comparator recipe
  • The Listening for vector layer features' events recipe