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

Creating a side-by-side map comparator

We are going to create a map comparator. The goal is to have two maps side-by-side from different providers and synchronize the same position and zoom level. The source code can be found in ch04/ch04-map-comparator. Here's a screenshot of our two synchronized maps, side-by-side:

Creating a side-by-side map comparator

How to do it…

To have two maps work in synchronization, perform the following steps:

  1. Create an HTML file with OpenLayers library dependencies. In particular, the markup for the two maps and separator should look like the following:
    <div id="js-map1"></div>
    <hr/>
    <div id="js-map2"></div>
  2. Create a custom JavaScript file and set up the shared view:
    var view = new ol.View({
      zoom: 5,
      center: [1252000, 7240000]
    });
  3. Instantiate the first map with the shared view, as follows:
    var map1 = new ol.Map({
      view: view,
      target: 'js-map1',
      layers: [
        new ol.layer.Tile({source: new ol.source.OSM()})
      ]
    });
  4. Finish off by instantiating the second map with the same shared view:
    var map2 = new ol.Map({
      view: view,
      target: 'js-map2',
      layers: [
        new ol.layer.Tile({
          source: new ol.source.Stamen({layer: 'watercolor'})
        })
      ]
    });

How it works…

Although the CSS importantly presents the two maps side-by-side, we're going to skip over the details of the styling implementation in order to focus on the JavaScript. Please view the accompanying source code for a complete understanding behind the layout.

You can see that, with minimal effort, we can mirror the zoom and position of the map by simply sharing the view. We caught wind of how easy this was to do when we looked at the Buffering the layer data to improve the map navigation recipe in Chapter 2, Adding Raster Layers, where the solution also had two maps in synchronization.

OpenLayers 3 has externalized the view from any given map instance. This loose coupling design decision makes techniques like this possible. The OpenLayers view object is referenced by both map instances; so, when one map moves, the underlying object updates. This means that the new values also get presented within the other map instance.

As a learning exercise, we can demonstrate how to manually subscribe to the zoom, and position change events from one map instance and reflect the changes onto the other map instance. In this example, the views would not be shared:

map1.getView().on(['change:resolution', 'change:center'], syncMap);

function syncMap(event) {
  if (event.type === 'change:resolution') {
    map2.getView().setZoom(event.currentTarget.getZoom());
  } else {
    map2.getView().setCenter(event.currentTarget.getCenter());
  }
};

For the first map instance, we get hold of the view (getView), subscribe to the change:resolution and change:center events, and provide a handler function, namely syncMap. The change:center event is published when the map position has moved, and the change:resolution event is published when the map zoom level has changed.

When these events get published, our handler is called and passed an event object. This object contains the type of event (event.type). This is important as our handler captures multiple types of events. So, using this information, we're able to determine what action to perform based on the type of event.

The event object also contains a reference to the view that has been modified, namely event.currentTarget. We use this reference to the view to either retrieve the new zoom value (getZoom) or the new center coordinates (getCenter). We reflect these new values on the second map instance using either the setZoom or setCenter methods from the view object (of the second map instance).

This code has been simplified for brevity, as you'd also need to register for the same event types from the second map instance so that the first map instance can also be updated.

As well as listening to events, we can also cease listening to the notifications if we wish to do so.

The ol.Observable class has the un method, as well as the on method. The un method allows us to unsubscribe our listener functions from the published events that we previously subscribed to.

If we continue with our manual subscription example, to unsubscribe from future changes in the zoom level, we can perform the following:

map1.getView().un('change:resolution', syncMap);

Similar to the on method, the un method allows you to unregister multiple listeners, so we could have passed an array of event types like we did for on, had we wanted to do this.

Our syncMap event handler will no longer be passed the zoom level event type.

There's also a method of ol.Observable, which is called once, that provides the ability to subscribe to an event, listen to just one published event of that type, and then automatically unsubscribe from future notifications.

There may be circumstances where this could prove very useful.

See also

  • The Using Bing imagery recipe in Chapter 2, Adding Raster Layers
  • The Implementing a work-in-progress indicator for map layers recipe
  • The Listening for vector layer features events recipe