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 and creating features from a WKT

As we're already discovering, OpenLayers comes with a great set of format helpers, which are used to read/write from/to different file data formats. GeoJSON, GML, and KML are some of the many available formats that we already explored.

If you read the Adding a GML layer recipe in this chapter, you will know that a vector layer can read the features stored in a file, specify the format of the data source, and place the contained features in the map.

For this recipe, we will programmatically create a polygon in the WKT format and then export the feature as WKT from the vector layer. You can read more about the WKT GIS format on Wikipedia (http://en.wikipedia.org/wiki/Well-known_text). The source code can be found in ch03/ch03-wkt-format/. Here's what we'll end up with:

Reading and creating features from a WKT

How to do it…

  1. Create a new HTML file with OpenLayers dependencies. In particular, add the HTML to create the map and side panel, as follows:
    <div id="js-map"></div>
    <div>
      <h1>WKT format</h1>
      <form>
        <button type="submit">Export layer</button>
        <textarea id="js-textarea"></textarea>
      </form>
    </div>
  2. Create a custom JavaScript file and build a polygon geometry using WKT:
    var wkt = [
      'POLYGON ((',
      '-8222044.493780339 4965922.635117188,',
      '-8217687.583168084 4967566.031225319,',
      '-8217572.927625656 4967527.812711176,',
      '-8216999.649913518 4967718.905281889,',
      '-8216082.405574095 4965616.887004048,',
      '-8218260.860880223 4964890.735235338,',
      '-8220324.660643922 4965349.357405049',
      '))'
    ];
  3. Convert the array to a string, as follows:
    var feature = new ol.format.WKT().readFeature(wkt.join(''));
  4. Create the map instance with a background raster layer and a vector layer, which we will add the feature to, as follows:
    var map = new ol.Map({
      view: new ol.View({
        zoom: 12,
        center: [-8224433, 4965464]
      }),
      target: 'js-map',
      layers: [
        new ol.layer.Tile({
          source: new ol.source.Stamen({layer: 'terrain'})
        }),
        new ol.layer.Vector({
          source: new ol.source.Vector({
            features: [feature]
          })
        })
      ]
    });
  5. Listen to form submissions and export the vector layer features as WKT:
    document.forms[0].addEventListener('submit', function(event) {
      event.preventDefault();
      var wktFormat = new ol.format.WKT();
      var features = map.getLayers().item(1)
                     .getSource().getFeatures();
      var wkt = wktFormat.writeFeatures(features);
    
      document.getElementById('js-textarea').value = wkt;
    });

How it works…

The map creation process will look familiar to the ones in the previous recipes. For the background raster layer, we used the terrain layer from Stamen, which, at the time of writing, only covers the extent of the USA. Let's continue by concentrating on the WKT OpenLayers code and functionality.

We created an array, namely wkt, that builds a polygon geometry. You can create many other geometry types from WKT, such as points, line strings, and so on. The parts of the WKT have been populated using an array because it's somewhat easier to read than a concatenated string over multiple lines.

var feature = new ol.format.WKT().readFeature(wkt.join(''));

The readFeature method expects the WKT to be a string. You'll see this as when we pass our array (wkt) to the WKT format method, readFeature, the JavaScript array method, join, converts our array of items into a single string by joining them together with an empty space.

As expected, we must instantiate a new instance of the WKT format (new ol.format.WKT()), which returns the format object. We chain on the reading feature method that we discussed earlier.

document.forms[0].addEventListener('submit', function(event) {
    event.preventDefault();
    var wktFormat = new ol.format.WKT();
    var features = map.getLayers().item(1)
                   .getSource().getFeatures();
    var wkt = wktFormat.writeFeatures(features);

    document.getElementById('js-textarea').value = wkt;
});

As part of the WKT format export, we attach a handler for the form submit event and prevent the default action.

We create a new WKT format object and store it in the wktFormat variable. We then retrieve the polygon feature from the vector layer. To do this, we return an ol.Collection object from the map via map.getLayers(). This collection has a useful method called item, which is used to select the array index of the layer. We know that our map has just two layers, of these, the second one is the vector layer, at index 1.

We continue to chain on another function called getSource, which retrieves the vector layer source. Then finally, we fetch all the features with the getFeatures method available from the vector source object.

Using the WKT format object (wktFormat), we serialize the OpenLayers features in the WKT format via the writeFeatures method. The content of the textbox is updated to include the exported WKT.

See also

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