Tuesday, April 17, 2018

Mapbox event listener

Leave a Comment

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

enter image description here

So what could be going on here?

2 Answers

Answers 1

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

Answers 2

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;     //...   } } 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment