如何检查Mapbox GL JS绘制状态

问题描述 投票:1回答:1

[如何在将new MapboxDraw对象发送到后端之前检查其状态?例如,要在用户尝试提交某些操作而不在地图上创建对象(在我的情况下为多边形)时向用户显示一些警告。

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!')
}

我实际上尝试使用以下代码解决此问题,因为正确多边形的长度值必须大于3点。

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

上面的代码仅在第一次执行中有效,但是在第二次执行中会导致错误,例如,如果用户尝试创建两个点的多边形,或者如果用户创建了一个多边形然后将其删除,则该错误

Uncaught TypeError: Cannot read property 'geometry' of undefined
mapbox-gl-js
1个回答
0
投票

您可以将Mapbox Draw中的许多事件附加到当前地图。

例如,map.on('draw.crete', function() {})将在创建多边形后执行。

您还可以使用draw.getMode()捕捉绘制的任何类型的多边形。

请参见下面的示例,希望对您有所帮助:)

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':

            break;
        case 'draw_polygon':

            break;
        case 'draw_line_string':

            break;
        default: alert('no draw options'); break;
    }

});

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

map.on('draw.delete', function(e) {
    // This will call once you delete the item
});
© www.soinside.com 2019 - 2024. All rights reserved.