reactjsarcgisesriarcgis-js-api

adding a layer on top of a WMTS BaseMap via user input (codesandbox example included)


I am trying to add a street level layer on top of my base map layer with arcgis. However, I can't seem to get my second layer of street names to render by toggling an input checkbox.

I was basing my solution on this example I found. esri link

This did not work however.

In the code pen example here, codepen

I was able to get my WMTS map to render, however I can't seem to add layers.

If I explicitly add the street layer link upon initialization of the Basemap, I do see it rendering. Otherwise I can't seem to have a dynamic way to add new layers on top of my basemap.

NOTE: map in codepen might take a minute to fully load up.


Solution

  • A quick fix is to useRef instead of useState for storing your map.

    Replace your map state declaration with the following:

    const mapRef = useRef(null);
    

    Change your map and view declaration to:

      const map = new Map({
        basemap: plainIGNBasemap,
        center: coordinates,
        // ...
        },
      });
    
      view = new MapView({
        container: ref.current, 
        map: map, //ensure to set this to your referenced map
        center: coordinates,
        // ...
      });
    
      mapRef.current = map;
    

    With the mapRef saved it can be accessed inside the code with mapRef.current. The MapView methods can be used in the same way the ArcGIS JS API documentation states. For example, to add your MapImageLayer on check, replace your code with the following:

    useEffect(() => {
      if (isChecked) {
        if (mapRef) {
          const imageLayer = new MapImageLayer({
            visible: true,
            url: "url goes here",
          });
          mapRef.current.add(imageLayer);
        }
      }
    }, [isChecked]);