khashashin
khashashin

Reputation: 1137

How to check Mapbox GL JS Draw state

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

Upvotes: 3

Views: 3106

Answers (1)

Parn
Parn

Reputation: 918

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
});

Upvotes: 4

Related Questions