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

Reading features directly using AJAX

The goal of this recipe is to show us how we can work directly with AJAX requests and load content from different data sources on the same vector layer.

OpenLayers allows us to read data from different origins and sources. We've seen that we can connect to a variety of services (such as WMS and WFS) and/or customize the request according to our needs (such as providing a URL directly pointing to a GML file).

We've seen that providing a URL and format type to the vector source is convenient and works for many cases. OpenLayers makes the AJAX request for us and automatically formats the response. However, there are times when we need even more control over the AJAX request and response, and this is where the loader function comes into play.

We have chosen to use jQuery to perform the AJAX requests. The requests will pull in two separate geometry files of different formats and add them both to the same vector layer. The source code for this recipe can be found in ch03/ch03-reading-features-from-ajax/. Here's the resulting geometry that we'll collate and render on the map:

Reading features directly using AJAX

How to do it…

Create your custom AJAX loader using the following instructions:

  1. Create an HTML file and add the OpenLayers dependencies and the jQuery library. Add a div element to hold the map.
  2. Next, initialize the map, add a raster layer, and center the viewport:
    var map = new ol.Map({
      view: new ol.View({
        zoom: 7,
        center: [-9039137, 3169996]
      }),
      target: 'js-map',
      layers: [
        new ol.layer.Tile({
          source: new ol.source.Stamen({layer: 'terrain'})
        })
      ]
    });
  3. Now, create a vector layer with a source that's responsible for making the multiple AJAX requests to fetch the two geometry files. Parse and then add the returned data to the vector source features list:
    var vectorLayer = new ol.layer.Vector({
      source: new ol.source.Vector({
        loader: function() {
          $.ajax({
            type: 'GET',
            url: 'points.wkt',
            context: this
          }).done(function(data) {
            var format = new ol.format.WKT({splitCollection: true});
            this.addFeatures(format.readFeatures(data));
          });
    
          $.ajax({
            type: 'GET',
            url: 'polygons.json',
            context: this
          }).done(function(data) {
            var format = new ol.format.GeoJSON();
            this.addFeatures(format.readFeatures(data));
          });
        }
      })
    });
  4. Add the vector layer to the map:
    map.addLayer(vectorLayer);

How it works…

Let's get straight to it and break down the important parts of this recipe:

source: new ol.source.Vector({
  loader: function() {

We use the loader property of the vector source to provide a custom function of type ol.FeatureLoader. Similar to the url property (which takes a function type of ol.FeatureUrlFunction), the loader function is also passed extent, resolution, and projection, respectively. We've omitted these as we don't make any use of them for our requests.

$.ajax({
  type: 'GET',
  url: 'points.wkt',
  context: this

With the help of jQuery, we set up an HTTP GET request, pointing towards a local geometry file, packed with points in the WKT format.

Within the loader function, the this keyword in JavaScript points to the vector source. We intend to use this reference when we add the returned features to the source from within the AJAX promise (done). jQuery offers a useful property called context that enables us to specify what the value of this references in the callbacks or promises. This saves us writing temporary variables or referencing the vector source in another way.

}).done(function(data) {
  var format = new ol.format.WKT({splitCollection: true});
  this.addFeatures(format.readFeatures(data));
});

Once the AJAX request has responded with success, our done promise is fired. The data parameter contains the content of the WKT file.

When the WKT format object is created, we pass a configuration object with the splitCollection property set to true. By default, OpenLayers will wrap the WKT geometries into a geometry collection, but we'd prefer each point to be classified as an individual feature in the feature collection. This is really just minor semantics for our example.

The features are processed (format.readFeatures) and added to the vector source (this.addFeatures), this is the equivalent of vectorLayer.getSource() here.

$.ajax({
  type: 'GET',
    url: 'polygons.json',
    context: this
  }).done(function(data) {
    var format = new ol.format.GeoJSON();
    this.addFeatures(format.readFeatures(data));
  });

This request is the same as the previous request, although this time around, we fetch a file containing data in the GeoJSON format. The features are added to the same vector layer.

When using the loader function, we are responsible for loading and adding the features to the layer ourselves.

There's more…

With the loader function, you have an opportunity to filter the list of features before adding them to a layer. This can be extremely useful if, for example, you're only interested in a subset of the feature list. You may filter based on geometry type, size, arbitrary properties, and so on.

See also

  • The Adding a GML layer recipe
  • The Adding features from a WFS server recipe
  • The Adding a KML layer recipe