1

I'm trying to add snap interaction to map using OpenLayers. Snap works on draw but only after drawing first point of polygon. Is there a way to make it snap while starting to draw the polygon? I tried adding snap before draw but then snap stops working, as it needs to be the last interaction added to the map. Code below

 const drawInteraction = new Draw({
      type: isLine?GeometryType.LINE_STRING: GeometryType.POLYGON,
     // source: <VectorSource>this._source2,
      style: new Style({
        stroke : new Stroke({
          color: this._strokeColor,
          width: this._strokeWidth
        })
      }),
      snapTolerance : 2
    })
    this._drawInteraction = drawInteraction;
    this._map.addInteraction(drawInteraction);

    //if snap enabled then add snap interaction
    if(this._enableSnap){
      this._snapInteraction = new Snap({
        source : this.snapVectorSource
       }
       )
       this._snapInteraction.setActive(true);
       this._map.addInteraction(this._snapInteraction);
    } 

1 Answer 1

0

Snap actually works even before drawing first point of polygon, but since there is no graphical representation of the current cursor point in the draw interaction style, you just don't see the snap action until something is drawn.

To see snap action even before first polygon point is drawn, you have to add image style to draw action style. Code could then look something like this:

const drawInteraction = new Draw({
  type: isLine?GeometryType.LINE_STRING: GeometryType.POLYGON,
  source: <VectorSource>this._source2,
  style: new Style({
    stroke : new Stroke({
      color: this._strokeColor,
      width: this._strokeWidth
    })
    image: new Circle({
      radius: 5,
      fill: new Fill({
        color: 'blue'
      })
    })
  }),
  snapTolerance : 2
});
1
  • Thanks, that worked. Commented Apr 4 at 14:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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