gpt4 book ai didi

javascript - 在 Leaflet 中创建事件控件的正确方法是什么?

转载 作者:行者123 更新时间:2023-11-30 09:25:00 26 4
gpt4 key购买 nike

我需要创建 L.Control 子类,它也是 L.Eventedinclude: [ L.Mixin.Events ] 有效,但显示警告它已被弃用,我需要从 L.Evented 继承。但我不能,因为我需要从 L.Control 继承。我该怎么办?

最佳答案

您可以将 L.Evented 混入您的自定义控件中,如下所示:

var CustomControl = L.Control.extend({
});
L.extend(CustomControl.prototype, L.Evented.prototype);

然后您可以触发事件并收听它们:

var cc = new CustomControl();
cc.on('myevent', function(s) {
console.log("event fired");
console.log(s);
});
cc.fire('myevent', {})

以及基于http://leafletjs.com/examples/extending/extending-3-controls.html#controls 的演示(点击 Leaflet 标志会触发一个事件)

var map = L.map('map', {
center: [40, 0],
zoom: 1
});

var positron = L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', {
attribution: "CartoDB"
}).addTo(map);

L.Control.Watermark = L.Control.extend({
onAdd: function(map) {
var img = L.DomUtil.create('img');

img.src = 'http://leafletjs.com/docs/images/logo.png';
img.style.width = '200px';

img.addEventListener('click', ()=> {
this.fire('myevent');
});
this.img

return img;
}
});
L.extend(L.Control.Watermark.prototype, L.Evented.prototype);

var mark = new L.Control.Watermark({ position: 'bottomleft' }).addTo(map);
mark.on('myevent', function() {
console.log('clicked');
})
html, body {
height: 100%;
margin: 0;
}
#map {
width: 100%;
height: 150px;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.3.1/leaflet.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.3.1/leaflet.js"></script>

<div id='map'></div>

关于javascript - 在 Leaflet 中创建事件控件的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49544644/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com