'How to drag a polygon in mapbox-gl-js?

I have a map with multiple polygons. The polygons need to move/update on user click/drag. The functionality I want is the same as this example: https://www.mapbox.com/mapbox-gl-js/example/drag-a-point/

I want to make the polygon draggable like the point example on mousedown, being able to move it on the map, updating the x/y coordinates of the polygon nodes throughout the event, but keeping the geojson size intact throughout the drag.

The point tutorial on Mapbox works well, but I'm unsure how to make it work with polygons.



Solution 1:[1]

  1. use draw.selectionchange to catch polygon selection / unselection. Remember the selected polygon (event features property, most likely it's features[0], since the selected feature is on top) in a variable; if you want the exact type, for polygon it's GeoJSON.Feature<GeoJSON.Polygon>;
  2. use draw.render - it corresponds in particular to a dragging: check - if the variable is not null - the required polygon info; you might need to additionally check the current draw mode (simple_select or direct_select) to exclude wrong triggering. Do whatever you need here;
  3. use draw.update: if action is move, it's a polygon 'draw end' event (apparently you may use the remembered variable, but you also have event features property at your disposal). Do whatever you need here.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1