Is there a easy way to move a polygon by its centroid on js API 4.x? I'm trying to implement a function where the user can drag a polygon of a graphicslayer on the screen
Solved! Go to Solution.
Here's a sample showing how you might allow points, polylines, and polygons to be dragged. In this example I'm using wherever the user clicked inside the polygon as the handle. You could easily use the centroid of the polygon as the origin/handle if you like: https://codepen.io/solowt/pen/QqoaeK?editors=1000#0
There's no built-in way to do this. In general, you need to clone a graphic, change the geometry on the clone, add clone to the layer, and then remove the old graphic. You can't just change the geometry. This will hopefully change in the future.
In terms of how you'd implement this, I would approach this by determining the difference in X and Y between "the handle" ie the centroid in your case, but possibly any point inside the polygon, and the current location of the mouse. Then you'll want to translate every vertex in every ring of the polygon by that amount in X and Y. I'll see if I can put together a simple example of this.
Here's a sample showing how you might allow points, polylines, and polygons to be dragged. In this example I'm using wherever the user clicked inside the polygon as the handle. You could easily use the centroid of the polygon as the origin/handle if you like: https://codepen.io/solowt/pen/QqoaeK?editors=1000#0
That's exact what I need, thank you