Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable an event listener in mapbox?

I am trying to have control over event listeners over a layer with Mapbox on React. map.off is supossed to do the trick, but it is not removing the onclick event in a layer. https://docs.mapbox.com/mapbox-gl-js/api/map/#map#off

But I am doing something wrong so I can't manage to remove the event. Here is what I have done so far...

To add the event I do this

map.on('click', 'building_footprints_click', addBuildingPopUp)

And to try to remove it I tried:

map.off('click', 'building_footprints_click', addBuildingPopUp);

map.off('click', 'building_footprints_click');

map.off('click', addBuildingPopUp);

But none of them are working. I read that I have to send to off the instance of the on event. So I tried to:

let event = map.on('click', 'building_footprints_click', addBuildingPopUp)

and the same three off operations as above but they don't work either

map.off('click', 'building_footprints_click', event);

map.off('click', 'building_footprints_click');

map.off('click', event);

And also the listener function, I have tried with:

const addBuildingPopUp = (e) => {} 

and 
function addBuildingPopUp (e) {} 

and 
let addBuildingPopUp = function building (e) {}

Here is a basic Stackblitz with a example of the non working function https://stackblitz.com/edit/react-5maykf?file=src/App.js

https://react-5maykf.stackblitz.io/

like image 909
Jorge Monroy Avatar asked Sep 17 '25 03:09

Jorge Monroy


1 Answers

Based on your stackblitz I can see that the problem is that you are trying to deregister a function that no longer exists.

For mapbox you need to register and deregister the same function. I mean map.on('mousemove', f1) and map.off('mousemove', f1) you need to ensure that f1 remains the same.

Let me explain that, whenever a react component renders, it does recreate all variables inside it's body unless it is part of a state variable, since the function addBuildingPopUp is created on every render mapboxgl does not deregister the event.

The only change you need to do is to ensure addBuildingPopUp remains the same, you should define outside React Component.

like image 139
pachonjcl Avatar answered Sep 18 '25 17:09

pachonjcl