1

I'm using a dragbox to capture coordinates from an openlayers 3 map. Is there a way to keep the dragbox visible once you release the mouse buttom and have it disappear only once you start a new dragbox?

1 Answer 1

2

Here is my implementation in v3.7.0:

You have two events listeners on the dragbox, boxend and boxstart. Use boxend to create a new polygon (look at this example), pass it the dragbox coordinates and then add it to the map. If you want to remove the dragbox once you start drawing a new one, remove the current active polygon from the map on boxstart.

Here is the code:

// Make the layer variable global to the two functions so we can access it in both functions
let layer;
dragBox.on('boxend', (evt) => {
  // Get the current dragbox coordinateds 
  let coordinates = dragBox.getGeometry().getCoordinates();
  // Create the polygon and pass the coordinates
  let polygonFeature = new ol.Feature(
                       new ol.geom.Polygon(coordinates));

  // Create the layer and style it as you like
  layer = new ol.layer.Vector({
    source: new ol.source.Vector({
      features: [polygonFeature]
    }),
    style: new ol.style.Style({
      stroke: new ol.style.Stroke({
        width: 1,
        color: [0, 0, 0, 1]
      }),
      fill: new ol.style.Fill({
        color: [127, 166, 59, 0.3]
      })
    })
  });

  // Assuming that you have a map instance, add the created layer to the map
  map.addLayer(layer);
});

// To remove the layer when you start drawing a new dragbox
dragBox.on('boxstart', (evt) => {
  map.removeLayer(layer);
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.