SOURCE

console 命令行工具 X clear

                    
>
console
var map = L.map('map', {
  center: [40, 116],
  zoom: 12
});

var layer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
  attribution: '&copy; <a href="https://osm.org">OpenStreetMap</a> contributors'
}).addTo(map)

//以下是方法对应的别名,map.on()和map.addEventListener的效果相同
//addEventListener = on, removeEventListener = off(...), clearEventListener = off()
//addOneTimeListener = once, fireEvent = fire, hasEventListeners = listens

//on和off都有两种方式,多个事件用空格隔开。注意,多次添加事件,响应函数也将多次执行,可一次性移除
btnAdd.onclick = function() {
  //map.on({click: handle_func(e), contextmenu: handle_func(e)});
  map.on('click contextmenu', function(e) {
    alert(e.latlng.lng);
  });
}

btnRemove.onclick = function() {
  //map.off({click: handle_func(e), contextmenu: handle_func(e)});
  //map.off(),无参数则remove all events
  map.off('click contextmenu');
}

btnOnce.onclick = function() {
  map.once('click', function(e) {
    alert(e.latlng.lng);
  });
}
//激发事件
btnFire.onclick = function() {
  var latlngPoint = new L.LatLng(40, 116);
  //注意第二个参数object: data,包含latlng,处理函数用e.latlng获取
  map.fire('click', {
     latlng: latlngPoint,
     layerPoint: map.latLngToLayerPoint(latlngPoint),
     containerPoint: map.latLngToContainerPoint(latlngPoint)
  });
}
//查看是否有click事件
btnHasListeners.onclick = function() {
  alert(map.listens('click'));
}
<div id="map" style="height: 300px; width: 300px">
</div>
<div style="height: 100px; width: 300px; background-color:#ccc;">
  <p><b>本测试以click事件为例</b></p>
  <input id="btnAdd" type="button" value="添加事件">
  <input id="btnRemove" type="button" value="移除事件">
  <input id="btnOnce" type="button" value="添加一次性事件">
  <input id="btnFire" type="button" value="激发事件">
  <input id="btnHasListeners" type="button" value="查看map是否有click事件">
</div>

本项目引用的自定义外部资源