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

Getting feature information from a data source

When a vector layer is populated with features, it can be very useful to query the data source in order to retrieve feature information. OpenLayers provides some methods from the vector source class (ol.source.Vector) that enable us to perform queries, such as finding out what features are within a custom extent (getFeaturesInExtent), or returning any features at a particular coordinate (getFeaturesAtCoordinate), as well as other useful types of queries.

We are going to create a map with a tile raster layer and a vector layer with features from a custom GeoJSON file. The polygon features will represent campsites within a region, each with some properties that can be extracted for display. We will call the getFeaturesAtCoordinate source query method when the map is clicked on and display the applicable feature information within overlay if a feature exists at this coordinate.

The source code can be found in ch05/ch05-feature-info-from-source, and here's a screenshot of what we'll end up with:

Getting feature information from a data source

How to do it…

In order to find out how to retrieve feature information from a data source, follow these steps:

  1. Create an HTML file with the OpenLayers dependencies and div to contain the map. In particular, add the markup for overlay and content:
    <div id="js-overlay" class="overlay">
    <ul>
    <li><strong id="js-ref"></strong></li>
    <li><span id="js-restrictions"></span></li>
    </ul>
    </div>
  2. Create a custom JavaScript file and set up a vector source with content from a local GeoJSON file:
    var vectorSource = new ol.source.Vector({
      url: 'geojson.json',
      format: new ol.format.GeoJSON({
        defaultDataProjection: 'EPSG:3857'
      })
    });
  3. Initialize map with a raster tile layer, vector layer, and view:
     var map = new ol.Map({
      view: new ol.View({
        zoom: 15, center: [872800, 6065125]
      }),
      target: 'js-map',
      layers: [
        new ol.layer.Tile({source: new ol.source.OSM()}),
        new ol.layer.Vector({source: vectorSource})
      ]
    });
  4. Cache some DOM elements that are accessed multiple times:
    var overlayElem = document.getElementById('js-overlay');
    var featureRefElem = document.getElementById('js-ref');
    var featureRestrictionsElem = document.getElementById(
      'js-restrictions'
    );
  5. Instantiate an instance of overlay, add it to map, and set the CSS display:
    var overlay = new ol.Overlay({
      element: overlayElem
    });
    map.addOverlay(overlay);
    overlayElem.style.display = 'block';
  6. Finish off by subscribing to the singleclick map event and display the feature information within overlay if appropriate:
    map.on('singleclick', function(event) {
      overlay.setPosition(undefined);
      var features =
        vectorSource.getFeaturesAtCoordinate(event.coordinate);
    
      if (features.length > 0) {
        overlay.setPosition(event.coordinate);
        featureRefElem.innerHTML = features[0].get('ref');
        featureRestrictionsElem.innerHTML =
          features[0].get('restrictions');
      }
    });

How it works…

We have excluded much of the HTML and all CSS from this recipe for brevity, but please take a look at the source code for the complete implementation.

Much of this recipe will be similar to earlier examples in this book, so let's narrow in on the map click event handler and the source query that we utilize:

map.on('singleclick', function(event) {
  overlay.setPosition(undefined);
  var features =
    vectorSource.getFeaturesAtCoordinate(event.coordinate);

We subscribe to the singleclick event published by the map object when a user clicks or taps on the map. The overlay method is passed an argument of undefined so that it's hidden until we know that we wish to display it.

We make use of the getFeaturesAtCoordinate source query method to determine whether or not a feature exists at the coordinate of the click event (event.coordinate). The result is stored in a variable, namely features.

    if (features.length > 0) {
    overlay.setPosition(event.coordinate);
    featureRefElem.innerHTML = features[0].get('ref');
    featureRestrictionsElem.innerHTML =  
      features[0].get('restrictions');
 }

Although we know that our data contains no overlapping features at any given coordinate, with other data sources this scenario may occur, which is why OpenLayers returns the result of the query as an array of features. We check whether the length of the array is greater than zero; if this is the case, we can infer that a feature is present at this particular coordinate.

The overlay is positioned at the coordinate via the setPosition method, and the overlay content is populated with the feature ref property and the restrictions property, both via the get method that ol.Feature inherits from ol.Object. The text is added to the relevant DOM elements using the JavaScript innerHTML method.

We can even use the getFeaturesAtCoordinate source query method with a coordinate, where a feature resides but is not currently visible from the viewport extent. It will still return the feature detected at this location.

There's more…

Other powerful data source queries exist, such as getClosestFeatureToCoordinate and getFeaturesInExtent, which could be very useful when developing mapping applications. I recommend that you visit the OpenLayers documentation (http://openlayers.org) to discover other useful methods and find out what these methods can do for you.

See also

  • The Adding WMS layers recipe in Chapter 2, Adding Raster Layers
  • The Getting information from a WMS server recipe
  • The Adding a GML layer recipe in Chapter 3, Working with Vector Layers
  • The Listening for vector layer features' event recipe in Chapter 4, Adding Controls