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

Exporting features as GeoJSON

In the earlier recipes, we saw how to read in data from different formats, such as GML and KML, but what about exporting data from a map? A user of your mapping application may want to get a copy of the vector layer data to use it somewhere else. Or perhaps, you're saving the state of a map and need to send the layer content to a server for persistent storage so that the same geometry can be retrieved later.

In this recipe, we will export the contents of a vector layer to the GeoJSON format. The source code can be found in ch03/ch03-export-geojson. Here's what we'll end up with:

Exporting features as GeoJSON

How to do it…

We are going to enable the use of an export button that will output the vector layer features as GeoJSON in a text box. Follow these steps to achieve this goal:

  1. Create the HTML file with OpenLayers dependencies. In particular, create the following:
    <div id="js-map"></div>
    <div>
      <h1>Exporting GeoJSON</h1>
      <form>
        <button type="submit">Export layer</button>
        <textarea id="js-textarea"></textarea>
      </form>
    </div>
  2. Create a JavaScript file, and initialize the map, view, and background raster layers:
    var map = new ol.Map({
      view: new ol.View({
        zoom: 5,
        center: [2103547, 6538117]
      }),
      target: 'js-map',
      layers: [
        new ol.layer.Tile({
          source: new ol.source.MapQuest({layer: 'osm'})
        })
      ]
    });
  3. Create a method for randomly picking an integer from a range of integers, as follows:
    var getRandomInt = function(min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min;
    };
  4. Build an array of randomly generated circular features, as follows:
    var features = [], numberOfFeatures = 0;
    
    while(numberOfFeatures < 10) {
      var circle = new ol.geom.Circle(
        ol.proj.fromLonLat(
          [getRandomInt(14, 23), getRandomInt(48, 54)]
        ), getRandomInt(4, 15) * 10000
      );
      var polygonCircle = ol.geom.Polygon.fromCircle(circle);
      features.push(new ol.Feature(polygonCircle));
      numberOfFeatures++;
    }
  5. Create the vector layer, add features to the vector source, and add this to map:
    var vectorLayer = new ol.layer.Vector({
        source: new ol.source.Vector({
            features: features
        })
    });
    map.addLayer(vectorLayer);
  6. Add a listener to the export button and export features as GeoJSON to the text box:
    document.forms[0].addEventListener('submit', function(event) {
        event.preventDefault();
        var format = new ol.format.GeoJSON();
        var features = vectorLayer.getSource().getFeatures();
        var geoJson = format.writeFeatures(features);
        document.getElementById('js-textarea').value = geoJson;
    });

How it works…

The JavaScript contains a method (getRandomInt) that picks an integer between a range at random. For more information on the inner workings of this method, visit http://stackoverflow.com/questions/1527803.

Let's focus on the new components that are utilized throughout this recipe:

var circle = new ol.geom.Circle(
  ol.proj.fromLonLat(
    [getRandomInt(14, 23), getRandomInt(48, 54)]
  ),
  getRandomInt(4, 15) * 10000
);

Within the while loop (that performs 10 iterations), we created a circle geometry each time. In order to programmatically create a set of differently sized circles, we've supplied a range of numbers representing longitude and latitude values that are randomly selected by getRandomInt. These ranges form an inaccurate bounding box around Poland, Europe.

The view uses the EPSG:3857 projection, so we use ol.proj.fromLonLat to convert the longitude and latitude values to this projection (which is the default if it is not specified as the second parameter).

We also create a randomly generated radius, which then gets multiplied by 10,000 so that it's clearly visible at the starting resolution.

var polygonCircle = ol.geom.Polygon.fromCircle(circle);

We convert the circle geometry to a regular polygon feature, which produces an approximated circle. This part may not be apparent, but GeoJSON (at the time of writing) doesn't support circle geometries yet, so we must convert it to a regular polygon so that it can be serialized and exported later on.

features.push(new ol.Feature(polygonCircle));

Note

You can increase the circular accuracy of ol.geom.Polygon.fromCircle by passing a higher number of sides as the second parameter. The default is 32.

The polygon circle is then converted into an ol.Feature instance so that OpenLayers can use it on the layer source, as follows.

document.forms[0].addEventListener('submit', function(event) {
    event.preventDefault();
    var format = new ol.format.GeoJSON();
    var features = vectorLayer.getSource().getFeatures();
    var geoJson = format.writeFeatures(features);
    document.getElementById('js-textarea').value = geoJson;
});

We add a submit event listener to the first and only form on the page, which prevents the default form submission.

We create a new instance of the GeoJSON format and store it in the format variable. The vector features are retrieved from the layer source via the helpful getSource method from the vector layer and through the getFeatures method from the vector source.

The GeoJSON is finally serialized using the writeFeatures method from the GeoJSON format provider, which expects an array of OpenLayers features. The GeoJSON string is then displayed inside the textarea element.

Displaying it in the textbox is one idea. You may decide to perform other actions with this data, such as posting it via AJAX to a server to save it, and so on.

See also…

  • The Adding a GML layer recipe
  • The Creating features programmatically recipe
  • The Reading features directly using AJAX recipe