I've added custom buttons to my MapBox map and they shop up correctly. 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
.
The 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'));
I see the expected result in my console (the test div).
So what could be going on here?
Start for free. Every product has a meaningful free tier so you can sign up and build without friction.
While Mapbox isn't entirely free, it has a generous free tier in its pricing packages that makes the service attractive for apps with a low volume of users. Free for up to 25,000 mobile users and 50,000 web loads. Customization of maps is easy.
If you need to find a location's latitude and longitude, you can use the Mapbox Search playground, which allows you to search for a location and retrieve its coordinates in longitude,latitude format.
To make sure that the click event is bind to the correct element, you can bind the event in the Class declaration instead.
Pass a callback for click event to the 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.
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()
?
Alternatively a setAction
in your CustomControl
like
setAction(action) {
this.container.addEventListener('click', action);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With