Skip to content

[Bug] Error: Source "mapbox-dem" cannot be removed while terrain is using it. #2553

@X-Titouan

Description

@X-Titouan

Description

This is the code from your example:

  return (
    <>
      <Map
        initialViewState={{
          latitude: 32.6141,
          longitude: -114.34411,
          zoom: 14,
          bearing: 80,
          pitch: 80,
        }}
        maxPitch={85}
        mapStyle="mapbox://styles/mapbox/satellite-v9"
        mapboxAccessToken={env.NEXT_PUBLIC_MAPBOX_ACCESS_TOKEN}
        terrain={{ source: "mapbox-dem", exaggeration: 1.5 }}
      >
        <Source
          id="mapbox-dem"
          type="raster-dem"
          url="mapbox://mapbox.mapbox-terrain-dem-v1"
          tileSize={512}
          maxzoom={14}
        />
      </Map>
    </>
  );

When you add reuseMaps to the Map component, and you navigate to another page (so you unmount Map)

You have this error:

Error: Source "mapbox-dem" cannot be removed while terrain is using it.

I can fix is creating a cleanup composant like :

function MapCleanup() {
  const { current: map } = useMap();

  React.useEffect(() => {
    return () => {
      if (map) {
        try {
          map.getMap().setTerrain(undefined);
        } catch (error) {
          console.warn("Error:", error);
        }
      }
    };
  }, [map]);

  return null;
}

And use it like:

  return (
    <>
      <Map
        reuseMaps
        initialViewState={{
          latitude: 32.6141,
          longitude: -114.34411,
          zoom: 14,
          bearing: 80,
          pitch: 80,
        }}
        maxPitch={85}
        mapStyle="mapbox://styles/mapbox/satellite-v9"
        mapboxAccessToken={env.NEXT_PUBLIC_MAPBOX_ACCESS_TOKEN}
        terrain={{ source: "mapbox-dem", exaggeration: 1.5 }}
      >
        <MapCleanup />
        <Source
          id="mapbox-dem"
          type="raster-dem"
          url="mapbox://mapbox.mapbox-terrain-dem-v1"
          tileSize={512}
          maxzoom={14}
        />
      </Map>
    </>
  );

But its a lot of lines... Would it be possible to add map.getMap().setTerrain(undefined); when reuseMaps unmount mapbox-dem source ?

Expected Behavior

No response

Steps to Reproduce

See my message up

Environment

  • Framework version: "react-map-gl": "^8.0.4",
  • Map library: "mapbox-gl": "^3.14.0",
  • Browser: Chrome 139.0.7258.138
  • OS: Ubuntu

Logs

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions