Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a Leaflet custom checkbox control

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);
like image 574
user2906420 Avatar asked Sep 10 '14 10:09

user2906420


2 Answers

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

like image 181
YaFred Avatar answered Sep 20 '22 09:09

YaFred


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

like image 45
Anton vBR Avatar answered Sep 20 '22 09:09

Anton vBR