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:


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:


The code I am using for polygon drawing is:

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


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


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();
    var feat = new ol.Feature({geometry: geom});

See how it works in this fiddle.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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