Shawn Goulet
Shawn Goulet

Reputation: 108

How to drag a polygon in the same fashion as the dragging a point mapbox-gl-js example?

I have a geojson polygon adding to the map with the click of a button. I also have the style of the polygon changing on the mousedown event on the geojson and the x/y coord pairs (the geojson geometry) printing to the console accessing it through the queryRenderedFeatures call on the API.

I am now wanting to make the polygon draggable like the point example (links below) on the mousedown event on the polygon and be able to move it on the map, updating the x/y coords of the polygon nodes throughout the mousedown event, but keeping the geojson size intact throughout the drag.

Is straight mapbox-gl-js the way to do this, or should I be feeding a pre-configured geojson polygon into a mapbox-gl-draw - draw polygon mode on a user's action?

Any suggestions or examples?

API Drag A Point Example

Drag A Point GitHub Code

Upvotes: 7

Views: 1526

Answers (1)

mehul chauhan
mehul chauhan

Reputation: 1802

Try this

   var isDragging = false;
var startCoords;

map.on('click', function(e) {
  var features = map.queryRenderedFeatures(e.point, { layers: ['polygon-layer'] });
  var polygon = features[0];
  if (!polygon) return;
  
  startCoords = polygon.geometry.coordinates[0];
});

map.on('mousedown', function(e) {
  isDragging = true;
});

map.on('mousemove', function(e) {
  if (!isDragging) return;
  
  var coords = map.unproject(e.point);
  var delta = {
    lng: coords.lng - startCoords[0],
    lat: coords.lat - startCoords[1]
  };
  
  polygon.geometry.coordinates[0] = polygon.geometry.coordinates[0].map(function(coord) {
    return [coord[0] + delta.lng, coord[1] + delta.lat];
  });
  
  map.getSource('polygon-source').setData(polygon);
});

map.on('mouseup', function(e) {
  isDragging = false;
});

the polygon is being stored as a GeoJSON feature, and the polygon layer and source are named 'polygon-layer' and 'polygon-source', respectively. You will need to adjust these names to match your setup.

Upvotes: 0

Related Questions