创建Leaflet自定义复选框控件

时间:2014-09-10 10:57:45

标签: javascript jquery map leaflet

我想创建一个自定义复选框控件,只需在jquery / javascript中设置一个标志:如果选中了flag =' clustered'或者如果未选中flag =' unclustered'。到目前为止,我在地图上有一个控件,但它不是一个复选框,如何获得复选框的状态 - 如果选中/取消选中。

代码:

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

2 个答案:

答案 0 :(得分:15)

您必须使用输入类型="复选框"创建表单元素。在你的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);

适用于此jsfiddle http://jsfiddle.net/FranceImage/ao33674e/

你也可以通过传单阅读本文的提示:https://github.com/Leaflet/Leaflet/blob/master/src/control/Control.Layers.js

答案 1 :(得分:0)

偶然发现了这一点,即使接受的答案将我指向了正确的方向,我还是对其进行了调整,以添加适当的css类。

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

结果:

enter image description here