Search code examples
mapboxmapbox-gl-jsreact-map-gl

How to load Terrain source and add to Mapbox map w/ React?


This is using the https://github.com/visgl/react-map-gl fork. Using vanilla JS, you use the 'load' callback to add a Source and then set the Terrain. I was able to replicate this using React and useEffect, but the solution doesn't feel right. How does one properly do this in React?


Solution

  • first a Source should be returned as a child of the map:

    { Source } from "react-map-gl";
        
    <Map ...>
      <Source 
        id="mapbox-raster-dem"
        type="raster-dem"
        url="mapbox://mapbox.mapbox-terrain-dem-v1"
        tileSize="512"
        maxzoom="14"/>
    </Map>
    

    and now you can specify the Terrain style inside the Map component:

    terrain={{
      source: "mapbox-raster-dem",
       exaggeration: 2,
    }}
    

    full code:

    const MapInstance = () => {
      return (
        <Map
          ...
          terrain={{
            source: "mapbox-raster-dem",
            exaggeration: 2,
          }}
        >
          <Source
            id="mapbox-raster-dem"
            type="raster-dem"
            url="mapbox://mapbox.mapbox-terrain-dem-v1"
            tileSize="512"
            maxzoom="14"
          />
        </Map>
      );
    };