[GIS] Removing events map.on(“click”…) from mapbox gl

mapboxmapbox-glmapbox-gl-js

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?

Best Answer

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.