10

I remove the layers with map.removeLayer("clusters"); but got this error

evented.js:111 The layer 'clusters' does not exist in the map's style and cannot be queried for features.

as I have map.on('click', 'clusters', function (e) { ... event. So how to remove this?

2
  • I have a similar question. So I have: window.onClick = function (e) {...} map.on('click', 'driver001', onClick); and map.on('click', 'driver002', onClick); and when I try to remove these event listeners with: map.off('click', 'driver001', onClick); and map.off('click', 'driver002', onClick); if only removes the event listeners from the last layer created is there anyway to remove the event listener from both layers? Thanks
    – todd tp
    Nov 16, 2018 at 16:13
  • Welcome to GIS StackExchange! As a new user please take the tour to learn about our focused Q&A format. This appears to not be an answer, but rather a similar issue to the original question. Please do not post non-answers -- you can start a new question and reference this one. This will allow more people to see it and possibly lend assistance.
    – SMiller
    Nov 16, 2018 at 17:02

2 Answers 2

16

First split out the click function so it can be referenced on it's own:

function onClick(e) {...}

Then register your on click with:

map.on('click', 'clusters', onClick);

Then just before you removeLayer, remove the event listener with

map.off('click', 'clusters', onClick);

See also https://www.mapbox.com/mapbox-gl-js/api/#map#off.

2
0

I have done it in React. I was trying something similar and come accross this thread. So in my case I wanted to remove an on click listener which would add some custom markers. Here is how I did it (for testing):

Attributes in File

const map = useRef(null);

map.current.on('click', (event) => addMarkerOnClick(event));
setTimeout(() => {
  console.log("Disabled")
  map.current.off('click', (event) => addMarkerOnClick(event));
}, 5000)

The above was how I had my code initially, it WONT work.

    map.current.on('click', addMarkerOnClick);
    setTimeout(() => {
      console.log("Disabled")
      map.current.off('click', addMarkerOnClick);
    }, 5000)

That's the solution.

For none React users, I suggest this:

// Attributes
let map = null

    map.on('click', addMarkerOnClick);
    setTimeout(() => {
      console.log("Disabled")
      map.off('click', addMarkerOnClick);
    }, 5000)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.