Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mapbox gl js disable controls

Tags:

mapbox-gl-js

Is there a way to hide/remove or disable controls such as the controls from mapbox-gl-draw?

I add the draw control as follows

    draw = mapboxgl.Draw({
    drawing: true,
    displayControlsDefault: false,
    controls: {
        polygon: true,
        trash: true
    }
});

map.addControl(draw);

Once a polygon is drawn I want to disable or hide the control, hence is no longer possible to draw another polygon.

Thanks a lot!

Gregor

like image 285
user3061553 Avatar asked Oct 31 '16 20:10

user3061553


2 Answers

You can actually disable the draw buttons (individually or as a group) with a little DOM interaction. In short, you can find the native CSS class for the draw menu ('mapbox-gl-draw_polygon', 'mapbox-gl-draw_point', etc.), add the disabled property, and add a CSS class with 'disabled'/grayed out styling. Example here: https://jsfiddle.net/emLs72zj/9/

// HTML

<div id="map">

</div>
<button id="disable-draw">
Disable Draw Btns
</button>

<button id="enable-draw">
Enable Draw Btns
</button>


// CSS

body { margin:0; padding:0; overflow:hidden;}
#map { position:absolute; top:20px; bottom:0; width:100%; }

.disabled-button {
  -webkit-filter: opacity(.3) drop-shadow(0 0 0 #FFF);
  filter: opacity(.3) drop-shadow(0 0 0 #FFF);
  cursor: default !important;
}


// JS

mapboxgl.accessToken = 'pk.eyJ1IjoieXVuamllIiwiYSI6ImNpZnd0ZjZkczNjNHd0Mm0xcGRoc21nY28ifQ.8lFXo9aC9PfoKQF9ywWW-g';
var sfmapbox = [-122.413692, 37.775712];

// Create a new dark theme map
var map = new mapboxgl.Map({
  container: 'map', // container id
  style: 'mapbox://styles/mapbox/outdoors-v9', //stylesheet location
  center: sfmapbox, // starting position
  zoom: 12, // starting zoom
  minZoom: 11,
});

map.on('load', function(){
        // create control
    var draw = mapboxgl.Draw({
        drawing: true,
        displayControlsDefault: false,
        controls: {
            polygon: true,
            trash: true
        }
    });
    // add control to map
    map.addControl(draw);

    var disableBtn = document.getElementById('disable-draw');
    var enableBtn = document.getElementById('enable-draw');

    var drawPolygon = document.getElementsByClassName('mapbox-gl-draw_polygon');

    disableBtn.onclick = (e) => {
        drawPolygon[0].disabled = true;
  drawPolygon[0].classList.add('disabled-button');
};

enableBtn.onclick = (e) => {
    drawPolygon[0].disabled = false;
  drawPolygon[0].classList.remove('disabled-button');
};
})
like image 126
Lauren Avatar answered Oct 10 '22 02:10

Lauren


Currently in 2020 you should use

mapboxDraw = new MapboxDraw({.... map.addControl(mapboxDraw);
map.removeControl(mapboxDraw);

like image 37
djdance Avatar answered Oct 10 '22 03:10

djdance