Interactions and drawing
Quick answer
This tutorial separates ol.control.Control from ol.interaction.Interaction and then builds editing tools with the latter. It creates ol.interaction.Draw for Point, LineString, Polygon and Circle, uses freehand, maxPoints and createBox geometryFunction, adds ol.interaction.Modify and ol.interaction.Snap with pixelTolerance, and handles select events. It also clones geometry before transform and measures with ol.sphere. Readers can assemble a coherent draw, edit and select workflow.
Key points
- Remove the previous Draw interaction before adding a new type; type has no setter.
- Clone the geometry before transform, otherwise the drawn feature itself is reprojected.
- Read evt.selected and evt.deselected from the Select interaction's select event.
Example
var drawSource = new ol.source.Vector();
var draw = new ol.interaction.Draw({
source: drawSource,
type: 'Polygon',
style: new ol.style.Style({
fill: new ol.style.Fill({ color: 'rgba(31,95,208,0.15)' }),
stroke: new ol.style.Stroke({ color: '#1f5fd0', width: 2 })
})
});
map.addInteraction(draw);
draw.on('drawend', function (evt) {
var geom = evt.feature.getGeometry();
console.log(geom.getType(), geom.getCoordinates());
});var drawBox = new ol.interaction.Draw({
source: drawSource,
type: 'Circle',
geometryFunction: ol.interaction.Draw.createBox()
});
Notes
- transform mutates geometry in place, so an uncloned result shifts right after drawing.
- Circle geometry stores centre and radius only, so convert it before exporting GeoJSON.
English edition written for Atlaslog. Code is taken from the original Chinese page and runs unchanged.
Atlaslog (2026). Interactions and drawing. https://www.jingweizhi.com/en/openlayers/tutorials/interaction-draw.html (accessed 2026-11-03).