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

Removing or cloning features using overlays

A common characteristic of web mapping applications is their ability to display information or perform actions that are related to the features on the map. By features, we mean any real phenomenon or aspect that we can visually represent with points, lines, polygons, and so on.

We can select a feature, retrieve its associated information, and choose to display it anywhere in our application layout. A common way to do this is using overlays.

In this recipe, we'll make it possible to clone and remove a feature from an overlay bubble that is displayed when clicking on a feature attached to the map. The source code can be found in ch03/ch03-removing-cloning-feature-overlay. This will look like the following screenshot:

Removing or cloning features using overlays

How to do it…

We will perform some feature manipulation from map overlays using the following instructions:

  1. Create an HTML file with OpenLayers dependencies, a div element to hold the map, and also the overlay and content, as follows:
    <div id="js-map"></div>
    <div id="js-overlay">
      <button id="js-clone">Clone</button>
      <button id="js-remove">Remove</button>
    </div>
  2. Create a custom JavaScript file and instantiate a new vector layer with three circle features, as follows:
    var vectorLayer = new ol.layer.Vector({
      source: new ol.source.Vector({
        features: [
          new ol.Feature(new ol.geom.Circle([2780119, 8437147], 900)),
          new ol.Feature(new ol.geom.Circle([2774826, 8433459], 850)),
          new ol.Feature(new ol.geom.Circle([2772686, 8438217], 999))
        ]
      })
    });
  3. Instantiate a map instance with view and layers, including our custom vector layer:
    var map = new ol.Map({
      view: new ol.View({
        zoom: 13,
        center: [2775906, 8433717]
      }),
      target: 'js-map',
      layers: [
        new ol.layer.Tile({
          source: new ol.source.MapQuest({layer: 'osm'})
        }),
        vectorLayer
      ]
    });
  4. Create an OpenLayers overlay from our custom HTML and add it to the map. Also, define a variable that we'll use throughout the code to reference the selected feature:
    var overlay = new ol.Overlay({
      element: document.getElementById('js-overlay')
    });
    map.addOverlay(overlay);
    var selectedFeature;
  5. Create an OpenLayers interaction to allow the selection of features:
    var select = new ol.interaction.Select({
        condition: ol.events.condition.click,
        layers: [vectorLayer]
    });
    map.addInteraction(select);
  6. Subscribe to the select event on the interaction and toggle the overlay accordingly:
    select.on('select', function(event) {
      selectedFeature = event.selected[0];
      if (selectedFeature) {
        overlay.setPosition(selectedFeature.getGeometry().getCenter())
      } else {
        overlay.setPosition(undefined);
      }
    });
  7. For the clone button, attach a click event handler and clone the circle:
    document.getElementById('js-clone')
      .addEventListener('click', function() {
        var circle = selectedFeature.clone();
        var circleGeometry = circle.getGeometry();
        var circleCenter = circleGeometry.getCenter();
    
        circleGeometry.setCenter([
            circleCenter[0] + circleGeometry.getRadius() * 2,
            circleCenter[1]
        ]);
        vectorLayer.getSource().addFeature(circle);
        overlay.setPosition(undefined);
        select.getFeatures().clear();
    });
  8. Finally, for the remove button, attach a click event handler and remove the feature:
    document.getElementById('js-remove')
      .addEventListener('click', function() {
        vectorLayer.getSource().removeFeature(selectedFeature);
        overlay.setPosition(undefined);
        select.getFeatures().clear();
    });

How it works…

We've omitted showing the CSS that styles the overlay as seen in the screenshot so that we can focus on the OpenLayers code. The complete code can be found within the accompanying source code for this book.

The map uses a raster base layer from MapQuest and the vector layer contains three arbitrary circle geometries of varying size. We will spend the rest of this section looking at the newly introduced concepts:

var overlay = new ol.Overlay({
  element: document.getElementById('js-overlay')
});
map.addOverlay(overlay);

OpenLayers provides a mechanism in order to display overlays or popups over a map at designated coordinates. This differs from controls, such as the zoom buttons, which are statically located on the viewport.

The ol.Overlay constructor is used to create our custom overlay bubble. We provide minimal configuration by passing in the DOM element that is used for the overlay content. OpenLayers wraps this content in an absolutely positioned div over the map. We finish off by assigning this overlay to the map with the addOverlay map method.

The overlay can be configured with other properties, such as autoPan and position. Map instances also contain a method to remove overlays, namely removeOverlay.

var select = new ol.interaction.Select({
  condition: ol.events.condition.click,
  layers: [vectorLayer]
});
map.addInteraction(select);

In order to make features (un)selectable, we use the OpenLayers interaction method called ol.interaction.Select. Some interactions are already enabled on the map by default, such as ol.interaction.MouseWheelZoom, among many others.

The interaction type expects a condition that is used to trigger the event. We used the click event here, which has a type of ol.MapBrowserEvent. The ol.events.condition object provides many other events, such as the ol.events.condition.singleClick event, which is the default for the select interaction. We avoided the default singleClick event because it has a delay of 250 ms (to ensure that it's not a double-click) in favor of the snapper click event that fires without any delay.

We restricted the layer coverage to just the vector layer containing the circles via the layers property. We finish by adding the interaction to the map via the addInteraction map method.

Using the select interaction has the benefit of automatically styling selected features differently, so that it's apparent they've been selected. You can customize the styling that's rendered on the map through the style property.

select.on('select', function(event) {
  selectedFeature = event.selected[0];
  if (selectedFeature) {
    overlay.setPosition(selectedFeature.getGeometry().getCenter());
  } else {
    overlay.setPosition(undefined);
  }    
});

Although the select interaction has been added to the map, we can't respond to the actions without first subscribing to some of its published events. We forge a subscription by using the on method to create an event handler for the select event.

When this event gets published, the event object contains the selected features (if there are any) inside the selected array. If applicable, it also contains any previously unselected features inside the deselected array. We store the first selected feature (as we're only expecting one to be selected at a time for this recipe) in the selectedFeature variable.

If a feature has been selected, then the overlay is positioned in the center of the circle geometry using the setPosition method. If there is no feature selected, then we ensure that the overlay is not visible. This is accomplished by passing undefined to setPosition.

var circle = selectedFeature.clone();
var circleGeometry = circle.getGeometry();
var circleCenter = circleGeometry.getCenter();

circleGeometry.setCenter([
  circleCenter[0] + circleGeometry.getRadius() * 2,
  circleCenter[1]
]);
vectorLayer.getSource().addFeature(circle);
overlay.setPosition(undefined);
select.getFeatures().clear();

There's a fair amount going on inside the click handler for the clone button. You'll see that we use many methods that are available from the ol.Feature instance.

We begin by cloning the selected circle with the clone method. With our copy of the circle, we cache the geometry (getGeometry) and center coordinates (getCenter) to variables that we reference later on.

The new circle geometry is centered at a different location via the setCenter method. The method expects an array of type ol.Coordinate. When we populate this array, we modify the x coordinate (circleCenter[0]) so that it's a full diameter width (of the original circle) away from the circle that we're cloning. The y coordinate remains untouched, resulting in the new circle horizontally adjacent to the original.

This new circle is then added to the vector layer source. To do this, we access the vector layer source through the getSource method from the vector layer, and then we chain on the addFeature vector source method passing in our circle. Once this feature has been added to the vector source, we close the overlay by setting the position to undefined.

The select interaction temporarily adds a copy of the circle feature, which provides the 'selected' style. To remove this feature from the map, we retrieve the selected features (getFeatures) from the select interaction, which returns an ol.Collection of features. We remove all these features from the collection using the clear method.

vectorLayer.getSource().removeFeature(selectedFeature);
overlay.setPosition(undefined);
select.getFeatures().clear();

Within the less complicated click event handler for the remove button, we gain access to the vector layer source (getSource) and remove the currently selected feature (stored in selectedFeature during the select event handler). As seen in the clone handler, we reset the overlay position in order to hide it from the map, and we also clear any temporary features that were held in the select interaction collection.

We covered some important ground here by introducing map interactions and some of the powerful benefits that they can provide to a mapping application. We'll get to explore other map interactions as this book progresses.

See also

  • The Using point features as markers recipe