'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]
- use
draw.selectionchange
to catch polygon selection / unselection. Remember the selected polygon (eventfeatures
property, most likely it'sfeatures[0]
, since the selected feature is on top) in a variable; if you want the exact type, for polygon it'sGeoJSON.Feature<GeoJSON.Polygon>
; - 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
ordirect_select
) to exclude wrong triggering. Do whatever you need here; - use
draw.update
: ifaction
ismove
, it's a polygon 'draw end' event (apparently you may use the remembered variable, but you also have eventfeatures
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 |