mapbox / mapbox/mapbox-gl-js

`loaded()` and `on('load')` event do not work as expected

Open
#6,707 20 comments 36 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

api :memo:
Dominant language
TypeScript
Stars
12.4k
Forks
2.4k
PR merge metrics
No merged PRs in 30d

Description

**mapbox-gl-js version**: 0.45.0

### Question

There are certain methods that you cannot call while the map is still loading, such as `map.addLayer()`. You can use the `map.on('load')` event to know when it is safe to call these methods, however there is no corresponding method like `map.ready()` for knowing that it is safe to call `map.addLayer()`. `map.loaded()` can also return false during other method calls, such as `map.setLayoutProperty()`, and you can safely call `map.addLayer()` when `map.loaded()` returns `false`. Also if `map.loaded()` returns `false` then `map.on('load')` only works the first time, so you need to track the initial load state yourself.

Every time I have tried to make a complex map with mapbox-gl I have hit some kind of frustrating bug that was related to loading state and these events. They have changed gradually over versions but they still don't work as expected.

It would be great if `mapbox-gl` could just track its ready state internally, so that calling `map.addLayer()` just worked as expected straight away. Either that or we need methods that correspond to load events. I want to do something like this:

```js
if (map.loaded()) {
map.addLayer(...)
} else {
map.on('load', () => map.addLayer(...))
}
```

But this will only work the first time (`map.on('load')` only fires once), but sometimes `map.loaded()` will return false if the map is moving.

### Links to related documentation

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the loading-state behavior around map.loaded(), map.on('load'), map.addLayer(), and map.setLayoutProperty() in the reported 0.45.0 scenario. Determine the intended ready-state and event semantics, then verify that the chosen behavior works both during initial loading and while the map is moving.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, typescript
Domain
frontend, web-dev
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.