2

I am starting to convert old code of OpenLayers 2 to OpenLayers 3. In the old version you could make polygon shape based of the amount of sides like in the example below:

http://jsfiddle.net/r9g1odce/4/

I was looking for the same functionality in OpenLayers 3 but couldn't find any... is there something I am missing?

The best example I found for drawing and modifying features is here but there is no square shape:

http://acanimal.github.io/thebookofopenlayers3/chapter07_07_editing_features.html

The code I am using for polygon drawing is:

drawInteraction = new ol.interaction.Draw({
    features: featureOverlay.getFeatures(),
    type: /** @type {ol.geom.GeometryType} */ ('Polygon') 
  });

map.addInteraction(drawInteraction);

The types can be found here: http://openlayers.org/en/v3.1.1/apidoc/ol.geom.html

1 Answer 1

2

You can easily recreate the functionality with ol.interaction.DragBox. The interaction has a boxend event, which propagates an object with a getGeometry() function.

The geometry can be added to a new feature, which can be added to the vector source. The geometry can be logged directly from the boxend event handler, but the source object also has an addfeature event.

To create a dragbox interaction, you have to define the condition on which the interaction activates (I think it is shiftKey by default), and the style of the box.

var interaction = new ol.interaction.DragBox({
    condition: ol.events.condition.noModifierKeys,
    style: new ol.style.Style({
        stroke: new ol.style.Stroke({
            color: [0, 0, 255, 1]
        })
    })
});

The geometry of the last dragged box then gets extracted by the event handler, and added to the vector source.

interaction.on('boxend', function(evt){
    var geom = evt.target.getGeometry();
    console.log(geom);
    var feat = new ol.Feature({geometry: geom});
    source.addFeature(feat);
});

See how it works in this fiddle.

1

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.