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

Creating features programmatically

Loading data from an external source is not the only way to work with vector layers. Imagine a web-mapping application where the user can create new features on the fly, such as landing zones, perimeters, areas of interest, and so on, and add them to a vector layer with some style. This scenario requires the ability to create and add the features programmatically.

In this recipe, we will take a look at some ways to create a selection of features programmatically. The source code can be found in ch03/ch03-creating-features/. The following screenshot shows some features that are created programmatically:

Creating features programmatically

How to do it…

Here, we'll create some features programmatically, without any file importing. Follow these instructions to find out how this is done:

  1. Start by creating a new HTML file with the required OpenLayers dependencies. In particular, add the div element to hold the map:
    <div id="js-map"></div>
  2. Create an empty JavaScript file and instantiate a map with a background raster layer:
    var map = new ol.Map({
      view: new ol.View({
        zoom: 3,
        center: [-2719935, 3385243]
      }),
      target: 'js-map',
      layers: [
        new ol.layer.Tile({
          source: new ol.source.MapQuest({layer: 'osm'})
        })
      ]
    });
  3. Create the point and circle features, as follows:
    var point = new ol.Feature({
      geometry: new ol.geom.Point([-606604, 3228700])
    });
    
    var circle = new ol.Feature(
      new ol.geom.Circle([-391357, 4774562], 9e5)
    );
  4. Create the line and polygon features:
    var line = new ol.Feature(
      new ol.geom.LineString([
        [-371789, 6711782], [1624133, 4539747]
      ])
    );
    var polygon = new ol.Feature(
      new ol.geom.Polygon([[
        [606604, 4285365], [1506726, 3933143],
        [1252344, 3248267], [195678, 3248267]
      ]])
    );
  5. Create the vector layer and add features to this layer:
    map.addLayer(new ol.layer.Vector({
      source: new ol.source.Vector({
        features: [point, circle, line, polygon]
      })
    }));

How it works…

Although we've created some random features for this recipe, features in mapping applications would normally represent some phenomenon of the real world with an appropriate geometry and style associated with it.

Let's go over the programmatic feature creation and how it is added to a vector layer:

var point = new ol.Feature({
  geometry: new ol.geom.Point([-606604, 3228700])
});

Features are instances of ol.Feature. This constructor contains many useful methods, such as clone, setGeometry, getStyle, and others. When creating an instance of ol.Feature, we must either pass in a geometry of type ol.geom.Geometry, or an object containing properties. We demonstrate both variations throughout this recipe.

For the point feature, we pass in a configuration object. The only property that we supply is geometry. There are other properties available, such as style, and the use of custom properties to set the feature attributes ourselves, which come with getters and setters.

The geometry instance belongs to ol.geom.Point. The ol.geom class provides a variety of other feature types that we don't get to see in this recipe, such as MultiLineString and MultiPoint. The point geometry type simply requires an ol.Coordinate type array (xy coordinates).

var circle = new ol.Feature(
  new ol.geom.Circle([-391357, 4774562], 9e5)
);

The circle feature follows almost the same structure as the point feature. This time, however, we don't pass in a configuration object to ol.Feature, but instead, we directly instantiate an ol.geom.Geometry type of Circle. The constructor takes an array of coordinates and a second parameter for the radius. 9e5 or 9e+5 is exponential notation for 900,000.

The circle geometry also has useful methods, such as getCenter, and setRadius.

var line = new ol.Feature(
  new ol.geom.LineString([
    [-371789, 6711782], [1624133, 4539747]
  ])
);

Note

Remember to express the coordinates in the appropriate projection, the one used by the view, or translate the coordinates yourself. We will cover working with feature styles in Chapter 6, Styling Features. For now, all features will be rendered with the default OpenLayers styling.

The only noticeable difference with the LineString feature is that ol.geom.LineString expects an array of coordinate arrays. For more advanced line strings, use the ol.geom.MultiLineString geometry type (more information can be found in the OpenLayers API documentation at http://openlayers.org/en/v3.13.0/apidoc/).

The LineString feature also has useful methods, such as getLength.

var polygon = new ol.Feature(
  new ol.geom.Polygon([[
    [606604, 4285365], [1506726, 3933143],
    [1252344, 3248267], [195678, 3248267]
  ]])
);

The final feature, a Polygon geometry type, differs slightly from the LineString feature in that it expects an ol.Coordinate type array within an array within another wrapping array. This is because the constructor (ol.geom.Polygon) expects an array of rings, with each ring being represented as an array of coordinates. Ideally, each ring should be closed.

The polygon feature also has useful methods, such as getArea, and getLinearRing.

map.addLayer(new ol.layer.Vector({
  source: new ol.source.Vector({
    features: [point, circle, line, polygon]
  })
}));

Note

The OGC's Simple Feature Access specification (http://www.opengeospatial.org/standards/sfa) contains an in-depth description of the standard. It also contains a UML class diagram where you can see all the geometry classes and hierarchy.

Finally, we create the vector layer with a vector source instance and add all four features to an array and pass it to the features property.

All the features that we've created are subclasses of ol.geom.SimpleGeometry. This class provides useful base methods, such as getExtent and getFirstCoordinate.

All features have a getType method that can be used to identify the type of feature, for example, 'Point', or 'LineString'.

There's more…

Sometimes, the polygon features may represent a region with a hole in it. To create a hollow part of a polygon, we use the LinearRing geometry. The outcome is best explained with the following screenshot:

There's more…

You can see that the polygon has a section cut out of it. To achieve this geometry, we must create the polygon in a slightly different way. Here are the steps:

  1. Create the polygon geometry, as follows:
    var polygon = new ol.geom.Polygon([[
      [606604, 4285365], [1506726, 3933143],
      [1252344, 3248267], [195678, 3248267]
    ]]);
  2. Create and add the linear ring to the polygon geometry:
    polygon.appendLinearRing(
      new ol.geom.LinearRing([
        [645740, 3766816], [1017529, 3786384],
        [1017529, 3532002], [626172, 3532002]
      ])
    );
  3. Create the completed feature, as follows:
    var polygonFeature = new ol.Feature(polygon);
  4. Finish off by adding the polygon feature to the vector layer:
    vectorLayer.getSource().addFeature(polygonFeature);

We won't break this logic down any further, as it's quite self-explanatory now that we're comfortable with geometry creation.

Note

The ol.geom.LinearRing feature can only be used in conjunction with a polygon geometry, and not as a standalone feature.

See also

  • The Adding markers to the map recipe
  • The Reading and creating features from a WKT recipe
  • The Styling features based on geometry type recipe in Chapter 6, Styling Features