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

Drawing in freehand mode

We showed you how to draw features back in Chapter 5, Adding Controls in the Drawing features across multiple vector layers recipe. OpenLayers also offers a freehand mechanism to draw features on vector layers using the ol.interaction.Draw class. Freehand mode can be defined as sketching something over the map without the defined accuracy and direction that you get when drawing a geometry type without freehand mode.

Having the flexibility to draw with more freedom can be useful in many application requirements. For example, it may be less arduous to create a path along a road with the continuous drawing flow of freehand, rather than having to click to add a point each time on the road as you go. With freehand mode, points are automatically added for you as you move the mouse in the direction that you want to draw in.

OpenLayers supports the freehand drawing of either polygons or lines. In this recipe, we're going to explore drawing polygons in freehand mode. After a polygon has been sketched, we will convert it to a more regular looking shape, either to a circle or a rectangle, based on what the user has selected from the radio inputs (refer to the following screenshot).

By default, the drawing freehand mode is enabled by holding down the Shift key, then keeping the mouse button pressed, and moving the cursor. When you're finished, release the Shift key and single click to complete the drawing. We'll use these defaults in our recipe.

The source code can be found in ch07/ch07-freehand-drawing, and we'll end up with something that looks like the following screenshot:

Drawing in freehand mode

How to do it…

  1. Create an HTML file and include the OpenLayers dependencies and a div element to hold the map. In particular, have the following HTML for the radio inputs:
    <input type="radio" name="convert" value="circle">
    <input type="radio" name="convert" value="rectangle" checked>
  2. Create a custom JavaScript file and instantiate a map instance with a view instance, a raster layer, and also a vector layer:
    var map = new ol.Map({
      view: new ol.View({
        zoom: 15, center: [-595501, 4320196]
      }), target: 'js-map',
      layers: [
        new ol.layer.Tile({source: new ol.source.OSM()}),
        new ol.layer.Vector({source: new ol.source.Vector()})
      ]
    });
  3. Set up the draw interaction for the polygon geometry type and add it to the map instance:
    var draw = new ol.interaction.Draw({
      source: map.getLayers().item(1).getSource(),
      type: 'Polygon'
    });
    map.addInteraction(draw);
  4. Subscribe to the drawend event and convert the sketch to either a rectangle or a circle geometry:
    draw.on('drawend', function(event) {
      var feature = event.feature;
      var convertTo = document.querySelector('[type="radio"]:checked').value;
    
      if (convertTo === 'rectangle') {
        feature.setGeometry(
          new ol.geom.Polygon.fromExtent(
            feature.getGeometry().getExtent()
          )
        );
      } else {
        var extent = feature.getGeometry().getExtent();
        var centre = ol.extent.getCenter(extent);
        var width = ol.extent.getTopRight(extent)[0] - ol.extent.getTopLeft(extent)[0];
        var radius = width / 2;
    
        feature.setGeometry(
          new ol.geom.Circle(centre, radius)
        );
      }
    });

How it works…

We've used the Bootstrap CSS framework to help style the top panel content, which we've excluded in the How to do it… section of this recipe. Please view the source code for the complete picture.

Most of the code will look similar to you from previous recipes, but we'll of course take a closer look at what's going on within the event hander for the draw interaction:

draw.on('drawend', function(event) {
  var feature = event.feature;
  var convertTo =
      document.querySelector('[type="radio"]:checked').value;

Once a freehand sketch has been completed, the drawend event is published, which our preceding handler subscribes to.

The event object holds reference to the drawn feature, which we store in a variable, namely feature. We store the user's conversion choice in the convertTo variable by querying the DOM for the radio input that's been selected, and then we retrieve the value of the input element. The value will either be 'rectangle' or 'circle'.

if (convertTo === 'rectangle') {
    feature.setGeometry(
      new ol.geom.Polygon.fromExtent(
        feature.getGeometry().getExtent()
      )
    );

If the user has selected this drawing to convert it to a rectangle, we update the geometry of the feature in place, using the setGeometry method from the ol.Feature instance. Inside this method, we provide a new geometry instance.

To create a new geometry instance from the extent of the sketched out feature, we use the helpful method, ol.geom.Polygon.fromExtent. This method takes a single parameter of the extent and returns an instance of ol.geom.Polygon, which is used as the replacement geometry for the feature.

var extent = feature.getGeometry().getExtent();
var centre = ol.extent.getCenter(extent);
var width = ol.extent.getTopRight(extent)[0] -
    ol.extent.getTopLeft(extent)[0];
var radius = width / 2;

feature.setGeometry(
  new ol.geom.Circle(centre, radius)
);

However, if the user wants to convert the sketch to a circle, we have a little more manual work to do.

We begin by retrieving the extent of the geometry in the same way as before. With extent, we can estimate what an accurate circle should be from the intention of the sketch. OpenLayers provides a bunch of methods that can be used when working with extents as a part of the ol.extent object.

The first of this is the self-explanatory ol.extent.getCenter method. The centre coordinate that is returned from this method will also be used to define the centre coordinate of our circle.

We then calculate the width of extent by taking the right-most point with the ol.extent.getTopRight method and subtracting it from the left-most point with the ol.extent.getTopLeft method. If we wanted to, we could have alternatively used the ol.extent.getBottomRight and ol.extent.getBottomLeft methods to provide the same desired result.

Both of these methods return a coordinate, an array of the ol.Coordinate type in the xy format. We're only interested in width, so we take the x values from each array by accessing the first index ([0]). The result, which is stored in the width variable, essentially provides the diameter for our circle.

When we construct a circle geometry, using the ol.geom.Circle constructor, the second argument expects a radius circle, not diameter, so we divide the width variable by two.

We finish by setting the new geometry on the feature in place, just like we did before.

Note

If you're looking to achieve similar functionality in OpenLayers 2, there's a tutorial at http://codechewing.com/library/create-circles-in-openlayers-using-freehand-mode/.

See also

  • The Drawing features across multiple vector layers recipe in Chapter 5, Adding Controls
  • The Modifying features recipe in Chapter 5, Adding Controls
  • The Styling interaction render intents recipe in Chapter 6, Styling Features