This sample demonstrates how to prevent users from drawing self-intersecting polylines using the Draw. To start drawing, click the button located just below the zoom controls.
The draw experience is built upon specific classes referred to as draw actions. A Draw action uses view events to generate a set of coordinates from which different types of geometries can be created. Each geometry type has a corresponding draw action class.
After initializing an instance of Draw, call draw.create() and a reference to a relevant draw action will be returned.
In this example, the draw.create()
method is called with the polyline
parameter when the user clicks the Draw polyline
button. We listen to different events on the PolylineDrawAction.
// draw polyline button
document.getElementById("line-button").onclick = () => {
view.graphics.removeAll();
// creates and returns an instance of PolyLineDrawAction
const action = draw.create("polyline");
// focus the view to activate keyboard shortcuts for sketching
view.focus();
// listen polylineDrawAction events to give immediate visual feedback
// to users as the line is being drawn on the view.
action.on(["vertex-remove", "cursor-update", "redo", "undo"], updateVertices);
})
Then we implement custom logic using the crossesOperator to determine when users are drawing self-intersecting polylines. Additional functionality provides visual feedback when the polyline crosses over itself.
// function that checks if the line intersects itself
function isSelfIntersecting(polyline) {
if (polyline.paths[0].length < 3) {
return false;
}
const line = polyline.clone();
// get the last segment from the polyline that is being drawn
const lastSegment = getLastSegment(polyline);
line.removePoint(0, line.paths[0].length - 1);
// returns true if the line intersects itself, false otherwise
return crossesOperator.execute(lastSegment, line);
}