[英]Mapbox event listener
I've added custom buttons to my MapBox map and they shop up correctly. 我已经为MapBox地图添加了自定义按钮,他们正确购物。 However when I add a click listener it does not work.
但是当我添加一个点击监听器时,它不起作用。 I see no error in my console.
我在控制台中看到没有错误。
The code looks like this: 代码如下所示:
const currentLocationControl = new CustomControl('current-location-control', 'GPS');
this.map.addControl(currentLocationControl, 'top-left');
document.getElementById('test').addEventListener('click', function (e) {
alert('test');
});
I execute this code in the mounted
method from vue.js
. 我从
vue.js
在mounted
方法中执行此代码。
The CustomControl: CustomControl:
export default class CustomControl {
constructor(className, text) {
this.className = className;
this.text = text;
}
onAdd(map){
this.map = map;
this.container = document.createElement('div');
this.container.id = 'test';
this.container.className = this.className;
this.container.textContent = this.text;
return this.container;
}
onRemove(){
this.container.parentNode.removeChild(this.container);
this.map = undefined;
}
}
When I console.log(document.getElementById('test'));
当我在
console.log(document.getElementById('test'));
I see the expected result in my console (the test div). 我在我的控制台(测试div)中看到了预期的结果。
So what could be going on here? 那么可能会发生什么?
To make sure that the click event is bind to the correct element, you can bind the event in the Class declaration instead. 要确保click事件绑定到正确的元素,您可以在Class声明中绑定事件。
Pass a callback for click event to the CustomControl 将click事件的回调传递给CustomControl
const clickCallback = function(e) {
alert(test);
};
const currentLocationControl = new CustomControl(
"current-location-control",
"GPS",
clickCallback
);
Class declaration: 舱位声明:
// add clickCallback to constructor
export default class CustomControl {
constructor(className, text, clickCallback) {
//...
}
onAdd(map) {
//...
this.container.onclick = clickCallback;
//...
}
}
It might very well be the element does not yet exist, depending on how map.addControl
works. 很可能元素尚不存在,具体取决于
map.addControl
工作原理。
Perhaps if you created a method in your CustomControl
to return the container, and instead of using document.getElementById
you'd use something like currentLocationControl.getContainer()
? 也许如果你在
CustomControl
创建了一个方法来返回容器,而不是使用document.getElementById
你会使用类似currentLocationControl.getContainer()
东西吗?
Alternatively a setAction
in your CustomControl
like 或者像
CustomControl
的setAction
setAction(action) {
this.container.addEventListener('click', action);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.