[GIS] How to programmatically start drawing in OpenLayers 4._

eventsjavascriptmap-drawingopenlayers

In openlayers there are 2 paradigms for drawing features one is to create a "draw interaction" that lets the user draw a feature and the other is to create the geometry and feature yourself–then add it to the layer.

I would like to programmatically start a polygon "interaction" drawing for the user by placing the first point. After which the user will place the remaining points. It therefore must be an "interaction".

This means I must simulate a user click or draw event that the openlayers api accepts as valid.

I've tried..

map.dispatchEvent(<clickevent>)
map.dispatchEvent(<drawstartevent>)

/*draw being ol.interaction.Draw*/
draw.dispatchEvent(<clickevent>)
draw.dispatchEvent(<drawstartevent>)

Best Answer

In non minified (ol-debug) version you can use function startDrawing_ (doc is here) which accepts event as a parametr. It uses only coordinates from that event, so it could be replaced by a simple object. Problem is I dont know how is this function named in minified version and also that name could change in time. Also it is not a very clean approach...

var draw = new ol.interaction.Draw({features:new ol.Collection([]), type:"Polygon"});
map.addInteraction(draw);
draw.startDrawing_({coordinates:[111,222]});