MapSnippets logo MapSnippets logo

Draw Interaction in OpenLayers

OpenLayers

Draw points, lines, and polygons in OpenLayers with ol.interaction.Draw writing to an ol.source.Vector, and measure areas with ol.sphere.getArea.

progress_activity Loading map...
var source = new ol.source.Vector();
var drawLayer = new ol.layer.Vector({
  source: source,
  style: new ol.style.Style({
    fill: new ol.style.Fill({ color: 'rgba(230, 57, 70, 0.2)' }),
    stroke: new ol.style.Stroke({ color: '#e63946', width: 2 }),
    image: new ol.style.Circle({ radius: 6, fill: new ol.style.Fill({ color: '#e63946' }) })
  })
});
var map = new ol.Map({
  target: 'map',
  layers: [
    new ol.layer.Tile({ source: new ol.source.XYZ({ url: 'https://api.maptiler.com/maps/streets-v4/256/{z}/{x}/{y}.png?key=YOUR_MAPTILER_KEY', attributions: '&copy; <a href="https://www.maptiler.com/copyright/">MapTiler</a>' }) }),
    drawLayer
  ],
  view: new ol.View({ center: ol.proj.fromLonLat([2.3522, 48.8566]), zoom: 13 })
});
var draw = new ol.interaction.Draw({ source: source, type: 'Polygon' });
map.addInteraction(draw);
draw.on('drawend', function(evt) {
  var geom = evt.feature.getGeometry();
  var area = ol.sphere.getArea(geom);
  console.log('Area: ' + (area / 1e6).toFixed(2) + ' km²');
});

How to draw shapes and measure areas in OpenLayers

ol.interaction.Draw adds drawing capabilities to the map. Users click to place vertices and double-click to finish the shape. The type parameter specifies the geometry type: 'Point', 'LineString', 'Polygon', or 'Circle'.

Drawn features are automatically added to the specified vector source. The drawend event fires when a shape is completed, providing access to the new feature and its geometry.

This example calculates the area of drawn polygons using ol.sphere.getArea(), which accounts for the Earth’s curvature.

Key APIs

API Description Docs
ol.interaction.Draw Interactive drawing tool openlayers.org
ol.sphere.getArea() Calculate geodesic area openlayers.org
drawend event Fired when drawing is completed openlayers.org

FAQ

How do I switch between drawing types?

Remove the current draw interaction with map.removeInteraction(draw), create a new one with the desired type, and add it back with map.addInteraction().

How do I delete a drawn shape?

Use source.removeFeature(feature) or source.clear() to remove all features. You can also add ol.interaction.Modify and ol.interaction.Snap for editing.

Common mistakes

  • Forgetting that double-click finishes the polygon, which can leave users unfamiliar with the UX stuck
  • Not removing the previous draw interaction before adding a new one with a different type
  • Using getArea() from ol.geom.Polygon instead of ol.sphere.getArea(). The geometry method returns projected area, not geodesic area.

Build maps using OpenLayers with AI

Generate code like this draw interaction in openlayers example using the OpenLayers skill in your IDE.