Create a Leaflet custom checkbox control

21,179

Solution 1

You have to create a form element with an input type="checkbox" in your controlDiv.

// create the control
var command = L.control({position: 'topright'});

command.onAdd = function (map) {
    var div = L.DomUtil.create('div', 'command');

    div.innerHTML = '<form><input id="command" type="checkbox"/>command</form>'; 
    return div;
};

command.addTo(map);


// add the event handler
function handleCommand() {
   alert("Clicked, checked = " + this.checked);
}

document.getElementById ("command").addEventListener ("click", handleCommand, false);

Works in this jsfiddle http://jsfiddle.net/FranceImage/ao33674e/

You can also do it the Leaflet way reading this for hints: https://github.com/Leaflet/Leaflet/blob/master/src/control/Control.Layers.js

Solution 2

Stumbled upon this and even though the accepted answer pointed me in the right direction I tweeked it to add appropiate css classes.

function toggleFunction(bool) {
  alert(bool)
}

var command = L.control({position: 'topright'});
command.onAdd = function (map) {
    var div = L.DomUtil.create('div');
    div.innerHTML = `
    <div class="leaflet-control-layers leaflet-control-layers-expanded">
      <form>
        <input class="leaflet-control-layers-overlays" id="command" 
          onclick=toggleFunction(this.checked) type="checkbox">
          Toggle
        </input>
      </form>
    </div>`; 
    return div;
};
command.addTo(mymap); //your map variable

Result:

enter image description here

Share:
21,179
user2906420
Author by

user2906420

Updated on November 05, 2020

Comments

  • user2906420
    user2906420 over 3 years

    I want to create a custom checkbox control which will simply set a flag in jquery/javascript: if checked the flag = 'clustered' or if unchecked flag = 'unclustered'. So far I have a control on the map but its not a checkbox and how do i get the state of the checkbox - if its checked/unchecked.

    code:

    function MapShowCommand() {
      alert("checked / unchecked"); //set flag
    }
    
    L.Control.Command = L.Control.extend({
        options: {
            position: 'topleft',
        },
    
        onAdd: function (map) {
            var controlDiv = L.DomUtil.create('div', 'leaflet-control-command');
            L.DomEvent
                .addListener(controlDiv, 'click', L.DomEvent.stopPropagation)
                .addListener(controlDiv, 'click', L.DomEvent.preventDefault)
            .addListener(controlDiv, 'click', function () { MapShowCommand(); });
    
            var controlUI = L.DomUtil.create('div', 'leaflet-control-command-interior', controlDiv);
            controlUI.title = 'Map Commands';
            return controlDiv;
                }
        });
    var test = new L.Control.Command();
    map.addControl(test);
    
  • user2906420
    user2906420 over 9 years
    Can you help by giving an example as I cannot make it work. with the above form.