Table of Contents for
Mastering OpenLayers 3

Version ebook / Retour

Cover image for bash Cookbook, 2nd Edition Mastering OpenLayers 3 by Gábor Farkas Published by Packt Publishing, 2016
  1. Cover
  2. Table of Contents
  3. Mastering OpenLayers 3
  4. Mastering OpenLayers 3
  5. Credits
  6. About the Author
  7. About the Reviewer
  8. www.PacktPub.com
  9. Preface
  10. What you need for this book
  11. Who this book is for
  12. Conventions
  13. Reader feedback
  14. Customer support
  15. 1. Creating Simple Maps with OpenLayers 3
  16. Structure of OpenLayers 3
  17. Building the layout
  18. Using the API documentation
  19. Debugging the code
  20. Summary
  21. 2. Applying Custom Styles
  22. Customizing the default appearance
  23. Styling vector layers
  24. Customizing the appearance with JavaScript
  25. Creating a WebGIS client layout
  26. Summary
  27. 3. Working with Layers
  28. Building a layer tree
  29. Adding layers dynamically
  30. Adding vector layers with the File API
  31. Adding vector layers with a library
  32. Removing layers dynamically
  33. Changing layer attributes
  34. Changing the layer order with the Drag and Drop API
  35. Clearing the message bar
  36. Summary
  37. 4. Using Vector Data
  38. Accessing attributes
  39. Setting attributes
  40. Validating attributes
  41. Creating thematic layers
  42. Saving vector data
  43. Saving with WFS-T
  44. Modifying the geometry
  45. Summary
  46. 5. Creating Responsive Applications with Interactions and Controls
  47. Building the toolbar
  48. Mapping interactions to controls
  49. Building a set of feature selection controls
  50. Adding new vector layers
  51. Building a set of drawing tools
  52. Modifying and snapping to features
  53. Creating new interactions
  54. Building a measuring control
  55. Summary
  56. 6. Controlling the Map – View and Projection
  57. Customizing a view
  58. Constraining a view
  59. Creating a navigation history
  60. Working with extents
  61. Rotating a view
  62. Changing the map's projection
  63. Creating custom animations
  64. Summary
  65. 7. Mastering Renderers
  66. Using different renderers
  67. Creating a WebGL map
  68. Drawing lines and polygons with WebGL
  69. Blending layers
  70. Clipping layers
  71. Exporting a map
  72. Creating a raster calculator
  73. Creating a convolution matrix
  74. Clipping a layer with WebGL
  75. Summary
  76. 8. OpenLayers 3 for Mobile
  77. Responsive styling with CSS
  78. Generating geocaches
  79. Adding device-dependent controls
  80. Vectorizing the mobile version
  81. Making the mobile application interactive
  82. Summary
  83. 9. Tools of the Trade – Integrating Third-Party Applications
  84. Exporting a QGIS project
  85. Importing shapefiles
  86. Spatial analysis with Turf
  87. Spatial analysis with JSTS
  88. 3D rendering with Cesium
  89. Summary
  90. 10. Compiling Custom Builds with Closure
  91. Configuring Node JS
  92. Compiling OpenLayers 3
  93. Bundling an application with OpenLayers 3
  94. Extending OpenLayers 3
  95. Creating rich documentation with JSDoc
  96. Summary
  97. Index

Accessing attributes

In the first example (ch04_getattribute), we will learn how to access attribute data stored in the features and communicate them to the user. We will use a very particular feature of OpenLayers 3: the overlay. As a first step, we will create some simple rules to be applied on our overlays:

.popup {
    border: 1px solid grey;
    background-color: rgba(255,255,255,1);
    border-radius: .5em;
}

Note

Overlays are geographically bounded HTML elements, which scale with the current resolution. They are stored separately from layers and other elements of the library, allowing us to have full control over them. As they are not parts of the canvas, we can easily style them with CSS.

Writing the code

For this task, we simply register a click event to our map, querying the underlying vector layers:

map.on('click', function (evt) {
    var pixel = evt.pixel;
    var coord = evt.coordinate;
    var attributeDiv = document.createElement('div');
    attributeDiv.className = 'popup';
    this.getOverlays().clear();

Firstly, we store the pointer's pixel and map coordinate value; then, we create a div element to store our attributes. Next, we clear out the existing overlays, implementing a lazy cancel effect. If the user opens a new overlay, the previous one disappears:

    this.forEachFeatureAtPixel(pixel, function (feature, layer) {
        var attributes = feature.getProperties();
        for (var i in attributes) {
            if (typeof attributes[i] !== 'object') {
                var attributeSpan = document.createElement('span');
                attributeSpan.textContent = i + ': ' + attributes[i];
                attributeDiv.appendChild(attributeSpan);
                attributeDiv.appendChild(document.createElement('br'));
            }
        }
        if (attributeDiv.children.length > 0) {
            this.addOverlay(new ol.Overlay({
                element: attributeDiv,
                position: coord
            }));
        }
    }, map, function (layerCandidate) {
        if (this.selectedLayer !== null && layerCandidate.get('id') === this.selectedLayer.id) {
            return true;
        }
        return false;
    }, tree);
});

Tip

The geometry of a feature is stored as a property; therefore, the getProperties method returns it. It can also return style objects related to a given feature. To avoid falsely mapping out these objects, you can type check every attribute if it is a primitive value with the JavaScript's typeof operator.

Next, we use the map's forEachFeatureAtPixel method to query the vector layers under a given pixel. The method is not an easy one; it requires five parameters from which two are functions. In order to have a better understanding in the method, you can set some break points in the method using the developer tools of your browser.

Note

The method's syntax is forEachFeatureAtPixel(pixel, callback, this for callback, layer filter, this for layer filter). It calls the layer filter function on all visible layers. If the filter function returns true, it queries the layer for features at the given pixel. Finally, it returns all the matched features and applies the callback function on them one by one.

In our callback function, we query the feature's attributes. Next, we iterate through its attributes object and append the attributes to our container element. If we have at least one attribute in our container in the end, we display it as an overlay. For the callback function, we specify this as the map object.

Tip

To iterate through plain objects, which have only properties inside, you can always use the in keyword with the for iterator, making your code simpler.

Next, we create our layer filter. As we only want to get features from the selected layer in the layer tree, we simply query every layer candidate against the layer tree's selectedLayer property. To make things more simple, we specify our layer tree object as the function's context. If you save the code and load the example, you can query features for their attributes. Don't forget to select the vector layer first:

Writing the code

The only drawback of this method is that you can select multiple features if they are under the same pixel. How many features can you select at once?

Writing the code