Mapbox-gl-js: Map#getLayer throws undefined error

Created on 12 Jun 2018  路  5Comments  路  Source: mapbox/mapbox-gl-js

mapbox-gl-js version: 0.45.0

browser: experienced in multiple browsers

Steps to Trigger Behavior

  1. Create new map new mapboxgl.Map()
  2. Wait for map.on('load', ...)
  3. Call map.addSource to load GeoJSON data then map.addLayer
  4. Call map.getLayer('layer-id')

Expected Behavior

Call should return the layer with the specified ID, or undefined if the ID corresponds to no existing layers.

Actual Behavior (intermittent)

We experience this intermittent error:

Cannot read property 'getLayer' of undefined

The stack points to this line:

n.prototype.getLayer = function(t) {
  return this.style.getLayer(t)
}

It's not easy to reproduce consistently and I don't have enough understanding of MapboxGL's internals to comprehend why this.style is still undefined considering my code is within the on('load', ...) callback. Let me know if a larger code sample would help.

All 5 comments

Closing this as I realized the mistake was mine. Sorry for the noise!

Closing this as I realized the mistake was mine. Sorry for the noise!

This has been most helpful..

I met the same mistake again , can you tell me how do you solve it that time?

@StuRuby Make sure you are spelling your layer name/id/source the same everywhere it is referenced. Since a lot of times you are just referring to the layer with a string, your IDE will not catch it if there is a spelling mistake. I suggest spelling the source and source layer exactly the same (they will not conflict). It will save you the trouble of needing to know which you need to reference in that moment.

Also, I had a weird thing where, when I defined the layer, I set the visibility of the layer to visible but it was not displaying. I ended up having to manually set visibility to visible.

In my features consumer in the render layer function:

this.onMapReady(() => {
    const { map } = this.props;
    map.setLayoutProperty("us-pipelines", "visibility", "visible");
});

In my case, I hadn't set the style correctly when initializing the map, so addSource threw this error.

Was this page helpful?
0 / 5 - 0 ratings