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

Exporting a map

The third useful canvas operation we will discuss is saving the content of the canvas as an image. As you may already know, traditionally, files can be saved by downloading them from a server. There are serious security considerations behind the restriction of saving anything to the hard drive that's created on the client side. However, there is no restriction in displaying a dynamically created image.

In this example, called ch07_print, we will create a control that dynamically creates an image based on the map canvas's context and opens it in a new tab. This way, we can download the image just like any other plain image from a web page. First, we will create a new control to save map states:

ol.control.Print = function (opt_options) {
    var options = opt_options || {};
    var _this = this;
    var controlDiv = document.createElement('div');
    controlDiv.className = options.class || 'ol-print ol-unselectable ol-control';
    var controlButton = document.createElement('button');
    controlButton.textContent = options.label || 'P';
    controlButton.title = options.tipLabel || 'Print map';
    var dataURL;
    controlButton.addEventListener('click', function (evt) {
        _this.getMap().once('postcompose', function (evt) {
            var canvas = evt.context.canvas;
            dataURL = canvas.toDataURL('image/png');
        });
        _this.getMap().renderSync();
        window.open(dataURL, '_blank');
        dataURL = null;
    });
    controlDiv.appendChild(controlButton);
    ol.control.Control.call(this, {
        element: controlDiv,
        target: options.target
    });
};
ol.inherits(ol.control.Print, ol.control.Control);

The control is very simple. If we push the button, it registers a one-time listener to the map object and converts the content of its canvas to a png image. More precisely, it converts it to a Base64 encoded URL of the png image, which can be opened by browsers, just like regular websites. After we have the URL, we call a synchronous rendering frame, making sure that the event occurs before we try to open our image. Finally, we simply open our image in a new tab.

Tip

When you try to open something in a new tab or window from JavaScript, your browser will most likely think that it's a popup and try to block it. As we work from a local server now, this problem does not occur, however, when you have to deploy such a feature, you should consider this behavior.

Next, we modify our map constructor a little bit. We deploy two new layers, adjust their views, and add our new control:

 map = new ol.Map({
    target: 'map',
    layers: [
        new ol.layer.Tile({
            source: new ol.source.TileWMS({
                url: 'http://demo.opengeo.org/geoserver/wms',
                params: {
                    layers: 'ned',
                    format: 'image/png'
                },
                wrapX: false,
                crossOrigin: 'anonymous'
            }),
            name: 'Elevation'
        }),
        new ol.layer.Tile({
            source: new ol.source.TileWMS({
                url: 'http://demo.opengeo.org/geoserver/wms',
                params: {
                    layers: 'nlcd',
                    format: 'image/png'
                },
                wrapX: false,
                crossOrigin: 'anonymous'
            }),
            name: 'Land Cover'
        })
    ],
    controls: [
        […]
        new ol.control.Print({
            target: 'toolbar'
        })
    ],
    view: new ol.View({
        center: [-8604363.40000572, 4741541.738586053],
        zoom: 9
    })
});

As you can see, we used an extra property when we constructed the layer objects. The crossOrigin property is very important if we want to access the pixel values of the canvas. This is also a security consideration that does not let us manipulate or export the content of a canvas if we have used a non-CORS image at any point in time. To mark the images of a layer as cross origin, we only have to set the layer's crossOrigin property to anonymous. If we do not implement this step, we end up with a tainted canvas, which we cannot export.

If you save the example and load it up, you can open the map's content in the form of a picture in a new tab:

Exporting a map