javascripthtmlmapbox-gl-jsmapbox-gl-draw

How can you use mapbox-gl-Draw to create rectangle of 8 points?


I have a unique issue to using Mapbox-gl-Draw. Mapbox Draw allows you to create a multi point polygon easily, however I need it to use only 8 points as an algorithm i use elsewhere accepts 8 lnglat elements. Im wondering if it is possible that when the draw button is clicked, that it displays a rectangle of 8 points on screen with the ability to drag each of the points?

Below is the expected outcome with one click of draw. Expected outcome Currently i can draw a rectangle but with only 4 points, each corner of the rectangle.


Solution

  • Rather than trying to mess with mapbox-gl-draw, you should just take the output, then add the midpoints programmatically. You can use turf's midpoint function for that purpose. Something like:

    const coords = rectangle.geometry.coordinates[0];
    const newcoords = [];
    coords.forEach((point, i) => {
       newcoords.push(point);
       if (i < coords.length - 1) {
           newcoords.push(midpoint(point, coords[i+1]).geometry.coords);
       }
    });
    rectangle.geometry.coordinates = newcoords;