mapbox / mapbox-gl-js

Interactive, thoroughly customizable maps in the browser, powered by vector tiles and WebGL
https://docs.mapbox.com/mapbox-gl-js/
Other
11.04k stars 2.21k forks source link

`Map#getLayer` returns `undefined` for the `custom` layer type #13239

Closed moong23 closed 1 month ago

moong23 commented 1 month ago

mapbox-gl-js version: 3.5.2

browser: chrome

Steps to Trigger Behavior

Link to Demonstration

https://codesandbox.io/p/sandbox/jovial-wing-f8y2xl?file=%2Fsrc%2FCustomMap.tsx%3A14%2C1 (think you need to log in to codesandbox to see this demo. Let me know if you want me to make a github repo-ed demo)

Expected Behavior

No re-rendering existing layer on state changes

Actual Behavior

when viewState changes, the layer tries to mount again.

stepankuzmin commented 1 month ago

@moong23, could you please make a standalone reproduction of this? I.e., using only GL JS?

moong23 commented 1 month ago

@stepankuzmin well haven't tried to use GL JS only, but i'll try my best 😃

Pessimistress commented 1 month ago

deck.gl uses map.getLayer(id) to determine if a layer already exists in the stack. Starting 3.5.2, this method is returning undefined for a layer that is already added.

Here is a minimal reproduction:


const map = new mapboxgl.Map({
  container: 'map',
  style: 'mapbox://styles/mapbox/light-v9',
  accessToken: MAPBOX_TOKEN
});

const layer = {
  id: 'my-layer',
  type: 'custom',

  onAdd() {
    console.log(`Layer ${this.id} is added`);
  },

  onRemove() {
    console.log(`Layer ${this.id} is removed`);
  },

  render() {}
}

map.on('styledata', () => {
  if (map.getLayer(layer.id)) {
    // already added
  } else {
    map.addLayer(layer);
  }
});

Log:

Layer my-layer is added
evented.ts:172
Error: Layer with id "my-layer" already exists on this map
    at Da.addLayer (style.ts:2118:38)
    at Map.addLayer (map.ts:2813:20)
    at Map.<anonymous> (app.js:38:9)
    at Map.fire (evented.ts:150:26)
    at Map.<anonymous> (map.ts:768:18)
    at Map.fire (evented.ts:150:26)
    at Da.fire (evented.ts:166:24)
    at style.ts:1202:18
    at h2 (load_sprite.ts:55:13)
    at load_sprite.ts:37:27
moong23 commented 1 month ago

thx @Pessimistress

stepankuzmin commented 1 month ago

Thanks, @Pessimistress. This is a bug.