Search code examples
openlayers

How to update a feature's geometry during the draw interaction


I am using ol.interaction.Draw to create a 2-point LineString. After clicking to set the first point I want the ability to programmatically move the first point before I click to set the final point. The reason is because the first point is associated with a feature on another layer that is moving. I want the line to "keep up" with the moving feature.

Is there a mechanism to change the first point’s geometry? I can update it in the geometryFunction but I can only get that called with a pointermove event. Seems hacky, but perhaps there’s a way to trigger that event without moving the mouse?

So does anyone have a way to manually change the geometry of the first point of the draw interaction?


Solution

  • You can update the interaction's sketch geometry while the mouse is not moving as demonstrated by adding

    setInterval(function () {
      if (sketch) {
        const geometry = sketch.getGeometry();
        if (geometry.getType() === 'LineString') {
          const coordinates = geometry.getCoordinates();
          coordinates[0][0] += 10;
          geometry.setCoordinates(coordinates);
        }
      }
    }, 100);
    

    to this OpenLayers example https://openlayers.org/en/latest/examples/measure.html

    Working example https://codesandbox.io/s/measure-forked-j6it12?file=/main.js

    However as soon as you move the mouse the default geometry function resets any changes made, so you will still need your custom geometry function.