Search code examples
drawingopenlayersstyling

Styling openlayers draw interaction


In the default openlayers draw interaction, there is no line segment which connects where your mouse is to the finish point (first image). When I set up a custom style, this segment is present which I don't want (second image). Does anyone know how I eliminate this final segment, like the default style does?

enter image description here enter image description here


Solution

  • You'll need a style function that can style points, lines and polygons and distinguish by the geometry's type. Important: the polygon style should only have a fill, not a stroke. Because the boundary of the polygon is a separate linestring. A minimal working style function for the draw interaction would look like this:

    var styles = {
      Point: new ol.style.Style({
        image: new ol.style.Circle()
      }),
      LineString: new ol.style.Style({
        stroke: new ol.style.Stroke()
      }),
      Polygon: new ol.style.Style({
        fill: new ol.style.Fill()
      })
    };
    function styleFunction(feature) {
      return styles[feature.getGeometry().getType();
    }