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 information from a WMS server

We've seen in earlier recipes that we can query external services for map tiles (WMS) and also for features (WFS). In addition to this, WMS servers can implement the GetFeatureInfo request. This type of request allows us to, given a point and some layer names that are configured at the WMS server, retrieve information from a feature; that is, we can get feature attributes from a layer, which is rendered as a raster image.

For example, there could be a WMS layer containing parking zones across your region, which can be drawn out as polygons over the map as part of the returned raster tiles. You could listen for a click event on the map and retrieve information from the WMS server in regards to the location that you clicked on. This may return data, such as parking fees, the name of the car park, how many spaces are still available, and so on.

OpenLayers makes this type of feature information request simple with a method called getGetFeatureInfoUrl, which is available on the source classes, ol.source.TileWMS and ol.source.ImageWMS.

We are going to create a map with a base layer and a raster layer containing data from a WMS server. When the user clicks or taps on an area of the map, we will make a feature information request to the WMS server and render the returned information below the map. The source code can be found in ch05/ch05-wms-feature-info, and we'll end up with something that looks like the following screenshot:

Getting information from a WMS server

How to do it…

In order to query for feature information from a WMS server, follow these instructions:

  1. Let's start by creating the HTML file with the OpenLayers dependencies and also jQuery. In particular, add the HTML for div to contain the feature information response:
    <div id="js-feature-info"></div>
  2. Create a custom JavaScript file and set up the WMS source instance:
    var bgsSource = new ol.source.TileWMS({
      url: 'http://ogc.bgs.ac.uk/cgi-bin/' +
           'BGS_Bedrock_and_Superficial_Geology/wms',
      params: {
        LAYERS: 'BGS_EN_Bedrock_and_Superficial_Geology'
      },
      attributions: [
        new ol.Attribution({
          html: 'Contains <a href="http://bgs.ac.uk">' +
            'British Geological Survey</a> ' +
            'materials &copy; NERC 2015'
        })]
    });
  3. Initialize map with a base layer, a WMS raster layer, and view:
    var map = new ol.Map({
      view: new ol.View({
        zoom: 7, center: [-146759, 7060335]
      }),
      target: 'js-map',
      layers: [
        new ol.layer.Tile({source: new ol.source.OSM()}),
        new ol.layer.Tile({source: bgsSource})
      ]
    });
  4. Cache the DOM element to a variable that'll be used to display the returned feature information:
    var $featureInfo = $('#js-feature-info');
  5. Subscribe to click events on the map, compose the URL, make the feature information request, and display the returned data on the page:
    map.on('singleclick', function(event) {
      var url = bgsSource.getGetFeatureInfoUrl(
        event.coordinate,
        map.getView().getResolution(),
        map.getView().getProjection(),
        {INFO_FORMAT: 'text/html'}
      );
    
      $.ajax({
        type: 'GET',
        url: url
      }).done(function(data) {
        $featureInfo.html(data.match(/<body>([\s\S]+)<\/body>/)[1]);
      });
    });

How it works…

This recipe contains HTML and CSS that have been excluded for brevity. Please take a look at the accompanying source code for the full implementation.

We've seen how to connect and request map tiles from a WMS server before in the Adding WMS layer recipe in Chapter 2, Adding Raster Layers, so let's focus on the map click handler, which contains some newly-introduced concepts:

map.on('singleclick', function(event) {
  var url = bgsSource.getGetFeatureInfoUrl(
    event.coordinate,
    map.getView().getResolution(),
    map.getView().getProjection(),
    {INFO_FORMAT: 'text/html'}
  );

We subscribed to the singleclick event on the map instance. Within our handler, we determine how the request URL will be structured. The WMS source instance (bgsSource) has the getGetFeatureInfoUrl method that expects the following four parameters:

  • Coordinate: This is acquired from the click event object (event.coordinate).
  • Resolution: This is acquired from the map's view via the getResolution method.
  • Projection: This is retrieved from the map's view via the getProjection method.
  • Parameters: This an object of key/value pairs to forge the request parameters. We have specified a supported format (from the WMS server) of text/html.

This method will return a string that we can use for the AJAX request coming up next:

$.ajax({
    type: 'GET',
    url: url
  }).done(function(data) {
    $featureInfo.html(data.match(/<body>([\s\S]+)<\/body>/)[1]);
  });

Note

A WMS server implements different request types, such as tile map requests that contain the parameter and value REQUEST=GetMap, respectively, as well as other parameters, such as a bounding box, layer name, and so on. It's important to know that the feature information differentiates requests with the following key/value parameter: REQUEST=GetFeatureInfo. Have a look at the network requests in any modern browser's development tools for more details.

Once we have the URL, we make the AJAX request using the jQuery ajax method. When the WMS server responds to the request, the done method is called and contains the response within the data argument.

We requested for a response to come back as media type text/html, as the content is conveniently structured in HTML tables that we can easily insert into our page without much further intervention. We are, however, only interested in the content of the body element from the response, so we extract only this using a JavaScript regular expression.

For example, here's what could be returned in raw form:

<!doctype html>
<head>
<title>Feature Info</title>
</head>
<body>
<table>...</table>
</body>
</html>

As per this example, we are only interested in the table element (within the body), as this contains all the feature information that we want.

We set up a regular expression to search for the opening and closing body tags and capture any characters in between, across multiple lines, which is what the [\s\S]+ part of the regular expression does. There's a great resource from Mozilla if you'd like to become more accustomed with JavaScript regular expressions at https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions.

The JavaScript method match returns an array containing the matched elements. As the regular expression captures the content between the opening and closing body tags (that's what the surrounding parentheses do), we access the second item in the returned array (index of 1). Undesirably, the zero index of the array returned from match contains the text, including the body tags.

The content is populated inside the div feature information on our page (refer to the recipe screenshot for an example of this output) via the html jQuery method.

See also

  • The Getting feature information from data source recipe
  • The Adding WMS layer recipe