Reputation: 544
I'm using ArcGIS JS 4.16 to allow users to draw a polygon on the map. The idea is that there will only be one polygon at any given time and when you connect two dots, it makes sense that it would complete the polygon. Double clicking or pressing "C" seems a bit more complex for the average use case.
const drawLayer = new GraphicsLayer();
const map = new Map({
basemap: 'streets-vector',
layers: [drawLayer],
});
const view = new MapView({
container: mapRef.current,
map: map,
center: [-73.93, 40.73],
zoom: 10,
});
const draw = new Draw({ view: view });
document
.getElementById('enableCreatePolygon')
.addEventListener('click', () => {
enableCreatePolygon(draw, view);
});
const enableCreatePolygon = (draw, view) => {
const action = draw.create('polygon');
action.on('vertex-add', (evt) => {
createPolygonGraphic(evt.vertices);
});
action.on('vertex-remove', (evt) => {
createPolygonGraphic(evt.vertices);
});
action.on('cursor-update', (evt) => {
createPolygonGraphic(evt.vertices);
});
action.on('draw-complete', (evt) => {
createPolygonGraphic(evt.vertices);
});
};
const createPolygonGraphic = (vertices) => {
view.graphics.removeAll();
const polygon = {
type: 'polygon',
rings: vertices,
spatialReference: view.spatialReference,
};
const graphic = new Graphic({
geometry: polygon,
symbol: {
type: 'simple-fill',
color: [51, 51, 204, 0.15],
style: 'solid',
outline: {
color: [51, 51, 204, 0.8],
width: 2,
},
},
});
Upvotes: 0
Views: 166
Reputation: 5270
I see two options, implement the "logic" or use SketchViewModel
where is it already implemented. Btw, with the "logic" I mean complete polygon when the last vertex is equal (with a tolerance) to the first vertex.
Take a look at this links,
ArcGIS JS API Docs - SketchViewModel
You can implement your own UI to interact with the model or use the SketchWidget
.
ArcGIS JS API Examples - Using custom UI or interaction
ArcGIS JS API Examples - Using SketchWidget
Upvotes: 2