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

Modifying features

As we saw in the previous recipe, Drawing features across multiple vector layers, it's quite straightforward to enable drawing capabilities for the user. However, what if the user needs to edit drawn features? Perhaps they want to move some vertexes around or move the entire feature to a new place. We'll take a look at these types of modifications throughout this recipe.

OpenLayers provides the ol.interaction.Modify class to move or add vertexes and the ol.interaction.Translate class to move whole features about.

The source code can be found in ch05/ch05-modifying-features, and here's a screenshot of what this will look like when it's done:

Modifying features

How to do it…

Learn how to modify existing features by following these steps:

  1. Create an HTML file with the OpenLayers dependencies and div to hold the map.
  2. Create a custom JavaScript file and begin by instantiating map with view, a raster tile layer, and a vector layer that retrieves features from a local GeoJSON file:
    var map = new ol.Map({
      view: new ol.View({
        zoom: 10, center: [-12035468, 4686812]
      }),
      target: 'js-map',
      layers: [
        new ol.layer.Tile({ source: new ol.source.Stamen({
          layer: 'terrain'
        })}),
        new ol.layer.Vector({
          editable: true,
          source: new ol.source.Vector({
            url: 'features.geojson',
            format: new ol.format.GeoJSON({
              defaultDataProjection: 'EPSG:3857'
            })
          })
        })
      ]
    });
  3. Set up the select interaction so that particular features can be selected for modification and add it to the map:
    var select = new ol.interaction.Select({
      filter: function(feature, layer) {
        return layer.get('editable') &&
          /Polygon|LineString/.test(
            feature.getGeometry().getType()
          );
      },
      condition: ol.events.condition.click
    });
    map.addInteraction(select);
  4. Finish off by setting up and adding the modify and translate interactions to the map:
    map.addInteraction(new ol.interaction.Modify({
      features: select.getFeatures()
    }));
    map.addInteraction(new ol.interaction.Translate({
      features: select.getFeatures()
    }));

How it works…

As you can see, adding this rich type of capability is made easy with OpenLayers. Once a user has selected a feature from the map, they can edit the feature or move it around. To spice things up a bit, we've added a filter mechanism to the select interaction, which checks a layer property and the geometry type before allowing the feature to be selected. Let's take a closer look at what's going on within the JavaScript:

new ol.layer.Vector({
  editable: true,
  source: new ol.source.Vector({
    url: 'features.geojson',
    format: new ol.format.GeoJSON({
      defaultDataProjection: 'EPSG:3857'
    })
  })
})

Within this instantiation of map, we set up a vector layer with a custom property of editable, which is used to identify whether or not this layer can be edited. We have also pulled in some GeoJSON that will populate the layer with some premade features.

var select = new ol.interaction.Select({
  filter: function(feature, layer) {
    return layer.get('editable') &&
      /Polygon|LineString/.test(
        feature.getGeometry().getType()
      );
  },
  condition: ol.events.condition.click
});

The select interaction has been configured with a filtering function. The function assigned to the filter property must be of type ol.interaction.SelectFilterFunction. This type of function is passed the feature and the layer as arguments, respectively, and it must return either true or false. If true is returned, the feature is eligible for selection and, thus, it is added to the collection. If false is returned, the feature will not be selected and it won't be added to the collection.

Our custom filtering function retrieves the layer property of editable via the get method and checks to see whether it evaluates to true. If so, a second conditional check is performed on the type of geometry.

The geometry object is retrieved from feature via the getGeometry method. Once we have the geometry, there's a method available to us called getType, which returns the geometry type as a string, for example, Polygon. This result is passed into the JavaScript test method, which runs the result against a regular expression. The /Polygon|LineString/ regular expression matches a string of either Polygon or LineString (the geometry type). The pipe (|) within this particular regular expression symbolizes an OR logical condition.

If both the layer is set as editable and the feature is of one of the accepted types, then the return statement evaluates to true; otherwise, this will be false.

In other words, if a vector layer hasn't been specifically marked as editable, then the feature cannot be modified. It also doesn't allow any other geometry types other than the two that were just discussed to be selected, and, subsequently, edited. This demonstrates how you can begin to structure read only or read/write layers, depending on your application requirements.

The condition property has been set to ol.events.condition.click to avoid the 250 ms delay that you get when accepting the default ol.events.condition.singleClick value for this property.

map.addInteraction(new ol.interaction.Modify({
  features: select.getFeatures()
}));
map.addInteraction(new ol.interaction.Translate({
  features: select.getFeatures()
}));

The modify and translate interactions follow the same setup. The features property of each are passed the currently selected features from the select interaction via select.getFeatures().

Although we didn't utilize any events within this recipe, the modify interaction publishes the self-explanatory modifyend and modifystart events. The translate interaction publishes similar events, namely translateend and translatestart, but it also publishes a translating event to subscribe to movement in between.

There's more…

When modifying features in OpenLayers 2, you were also able to effortlessly rotate and resize them. At the time of writing, this functionality hasn't been directly ported across to version 3.

However, there's an interesting function called applyTransform from the ol.geom.SimpleGeometry base class, which is inherited by most of the geometry types, such as ol.geom.Polygon. This function can be used to manually transform each coordinate of the geometry in order to modify the feature in place.

The function is of type ol.TransformFunction, which is passed the current array of coordinates and must return the output array of coordinates to be used. There's nothing to stop you performing some creative transforming here to imitate some missing functionality that you've become accustomed to in OpenLayers 2. This is, however, an advanced discussion, and unfortunately, it won't be covered in this book.

See also

  • The Drawing features across multiple vector layers recipe
  • The Adding and removing controls recipe
  • The Listening for vector layer features' event recipe in Chapter 4, Working with Events