Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check Mapbox GL JS Draw state

Tags:

mapbox-gl-js

How can you check the state of a new MapboxDraw object before sending it to the backend? For example, to show the user some warnings when he tries to submit some actions without creating an object (in my case a polygon) on the map.

this.draw = new MapboxDraw({
    controls: {
        trash: true,
        polygon: true
    },
    defaultMode: 'draw_polygon',
    displayControlsDefault: false,
})

# sudocode
if (user has not created a polygon on the map) {
    alert('You must create a polygon before submitting the form!')
}

I actually tried to solve this with the following code, because the length value of the correct polygon must be more than 3 points.

if (draw.getAll().features[0].geometry.coordinates[0].length <= 3) {
    alert('You must create a polygon before submitting the form!')
}

The above code only works in the first execution, but in the second execution it causes an error e.g if user tries to create a Polygon of two points or if user creates one polygon and then removes it

Uncaught TypeError: Cannot read property 'geometry' of undefined
like image 757
khashashin Avatar asked Nov 18 '25 09:11

khashashin


1 Answers

You can attach many events from Mapbox Draw to your current map.

For example, map.on('draw.crete', function() {}) This will execute once 1 polygon was already created.

You can also use draw.getMode() for catching any type of polygons you draw.

See below example, Hope it helps :)

var draw = new mapboxDraw({

    displayControlsDefault: false,
    controls: {
        point: true,
        polygon: true,
        line_string: true,
        trash: true
    }

});

map.on('draw.create', function(e) {

    var drawMode = draw.getMode();
    var drawnFeature = e.features[0];

    switch (drawMode) {
        case 'draw_point':
            // Draw point here
            break;
        case 'draw_polygon':
            // Draw polygon here
            break;
        case 'draw_line_string':
            // Draw linestring here
            break;
        default: alert('no draw options'); break;
    }

});

map.on('draw.update', function(e) {
    // This will call once you edit drawn polygon
});

map.on('draw.delete', function(e) {
    // This will call once you delete any polygon
});
like image 199
Parn Avatar answered Nov 20 '25 11:11

Parn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!