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

Zooming to the extent of a layer

When a group of features coexist on a vector map layer, such as circles and polygons, they make up a shared extent, which is also known as a bounding box. This rectangular extent accommodates all the geometries. It can be useful to acquire the extent of such a group of features so that we can reposition the map at optimal resolution for the point of interest, which is exactly what we will do in this recipe.

We will place some features on the map at low resolution, but initially, we will configure the map resolution to start much higher. The group of features will appear small to begin with, but we'll provide a button that conveniently pans and zooms the user much closer to the group of features, based on their combined extent.

The source code can be found in ch03/ch03-zoom-to-extent/. We'll end up with something that looks like the following screenshot:

Zooming to the extent of a layer

How to do it…

Discover how you can zoom to the extent of some features on a layer using the following instructions:

  1. Create an HTML file with OpenLayers dependencies, a div element to hold the map, and also the panel to house the button:
    <div id="js-map"></div>
    <div>
      <button id="js-zoom">Zoom to extent</button>
    </div>
  2. Create a custom JavaScript file and create a raster layer for the background mapping:
    var rasterLayer = 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/cycle/' +
             '{z}/{x}/{y}.png'
      })
    });
  3. Create a vector layer with some geometries, as follows:
    var vectorLayer = new ol.layer.Vector({
      source: new ol.source.Vector({
        features: [
          new ol.Feature(new ol.geom.Circle([-376645, 7762876], 200)),
          new ol.Feature(new ol.geom.Circle([-375955, 7762195], 200)),
          new ol.Feature(new ol.geom.Circle([-376953, 7761632], 200))
        ]
      })
    });
  4. Instantiate a new map:
    var map = new ol.Map({
      view: new ol.View({
        zoom: 11,
        center: [-372592, 7763536]
      }),
      target: 'js-map',
      layers: [rasterLayer, vectorLayer]
    });
  5. Finally, add the button click handler and logic to recenter the map, as follows:
    document.getElementById('js-zoom')
      .addEventListener('click', function() {
        map.beforeRender(
          ol.animation.pan({
            source: map.getView().getCenter(),
            duration: 150
          }),
          ol.animation.zoom({
            resolution: map.getView().getResolution(),
            duration: 500,
            easing: ol.easing.easeIn
          })
        );
          map.getView().fit(
       vectorLayer.getSource().getExtent(), map.getSize()
     );
    });

How it works…

Let's concentrate on what happens when the button is clicked, as this is where the OpenLayers code is utilized to relocate the map:

  map.beforeRender(
    ol.animation.pan({
      source: map.getView().getCenter(),
      duration: 150
    }),
    ol.animation.zoom({
      resolution: map.getView().getResolution(),
      duration: 500,
      easing: ol.easing.easeIn
    })
  );

Within the click handler, we start off by adding two animation pre-render functions (ol.animation.pan and ol.animation.zoom). We are momentarily going to be relocating the map view center position and zoom level based on the extent of the features, and we wish to perform this change through graceful transitions. The details of these types of transition behaviors and how they work have previously been covered in the Moving around the map view recipe in Chapter 1, Web Mapping Basics.

map.getView().fit(
   vectorLayer.getSource().getExtent(), map.getSize()
);

The map view (retrieved via the getView map method) contains a method called fit. The purpose of fit is to accommodate the given geometry or extent into a customized area (normally the same size of map viewport, but it doesn't have to be).

The fit method expects the first parameter to be one of two types, of which, we're interested in the type ol.Extent. This type is just an array of coordinates that make up the bounding box of our features. The vector source has a method called getExtent that enables us to retrieve this information. We pass in the resulting ol.Extent array as the first parameter.

The second parameter of fit expects a type of ol.Size, which is simply an array containing the width and height of the box in pixels. We want the extent of the features to fit as best they can into the viewport of the map, so we use the getSize map method, which returns the size in the desired format.

The fit method optionally takes a third parameter—an object of configurable properties, such as minResolution, which can be used to determine the minimum resolution that you'd like to see the extent of the features at when this function is called.

The fit method will automatically adjust the map view at the most optimal resolution that's available so that all features are in sight.