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

Adding vector layers with the File API

The HTML5 File API makes it possible for us to load nearly any kind of file from our hard drive to a browser and process these files with JavaScript. It has capabilities way beyond our use case (it can even handle binary files); thus, it is advisable for every frontend developer to look into it in further detail. The files for this example are named ch03_fileapi.

First, we create a new form as usual. You can grab it from the HTML file.

Creating the interface

The basic interface to access our new functionality is the same, as shown in the previous examples. First, we extend our layer constructor, adding a new button to the layer tree:

var layerTree = function (options) {
[…]
        controlDiv.appendChild(this.createButton('addvector', 'Add Vector Layer', 'addlayer'));
[…]
};

Next, we create a new rule for its button class in our CSS file:

.layertree-buttons .addvector {
    background-image: url(../../res/button_vector.png);
}

We also add a new event listener to our init function to link the form to our object:

document.getElementById('addvector_form').addEventListener('submit', function (evt) {
    evt.preventDefault();
    tree.addVectorLayer(this);
    this.parentNode.style.display = 'none';
});

Adding a new button to the layer tree, which is based on our knowledge from the previous example, is simple. If you save the code and load it, you will see the new option in the button container:

Creating the interface

Building the method

As usual, the method accepts a form as an argument. As you have seen in the HTML file, the parameters are the usual ones, with one exception: the format. We use some predefined formats for our users to choose from and construct our new layer accordingly. First, we start our method by initializing some essential parameters and constructing a new file reader:

layerTree.prototype.addVectorLayer = function (form) {
    var file = form.file.files[0];
    var currentProj = this.map.getView().getProjection();
    var fr = new FileReader();
    var sourceFormat;
    var source = new ol.source.Vector();

File readers, similar to AJAX requests, are asynchronous. We have to register a listener to the file reader's load event to reliably get all of the fetched data:

Note

The easiest way to get access to files is using an input element with a file type. The element has multiple file supports; hence, we have to grab the first element from its file array.

    fr.onload = function (evt) {
        var vectorData = evt.target.result;
        switch (form.format.value) {
            case 'geojson':
                sourceFormat = new ol.format.GeoJSON();
                break;
            case 'topojson':
                sourceFormat = new ol.format.TopoJSON();
                break;
            case 'kml':
                sourceFormat = new ol.format.KML();
                break;
            case 'osm':
                sourceFormat = new ol.format.OSMXML();
                break;
            default:
                return false;
        }
        var dataProjection = form.projection.value || sourceFormat.readProjection(vectorData) || currentProj;
        source.addFeatures(sourceFormat.readFeatures(vectorData, {
            dataProjection: dataProjection,
            featureProjection: currentProj
        }));
    };

When the data is available to be processed, we assign it to a variable. Based on the user's choice, we construct a format object and then try to guess the data's projection. Note that the order is important. First, we check whether the user has provided a projection by enabling manual overriding. We start guessing whether the form's projection field is empty. As all of the spatial formats have some way to store their projection, we try to access it. If we have no luck, we default the projection to our map's projection. Finally, we finish our method by telling the file reader to start reading, and while it's working, we create the layer and add it to the map:

Tip

TopoJSON is the new cutting-edge ASCII format to store vector data. It reduces redundancy in the coordinates by mapping topological connections, and it further decreases the file size by quantizing the coordinates. If you are not obligated to use a specific format, always consider using TopoJSON.

    fr.readAsText(file);
    var layer = new ol.layer.Vector({
        source: source,
        name: form.displayname.value,
        strategy: ol.loadingstrategy.bbox
    });
    this.addBufferIcon(layer);
    this.map.addLayer(layer);
    this.messages.textContent = 'Vector layer added successfully.';
    return this;
};

You can try out our new functionality with the vector layers that are located in the code appendix's res folder. All of the layers are in the EPSG:4326 projection.