Search code examples
reactjsmapboxpolygon

Adding multiple style layers in Mapbox / React js


I'm using mapbox gl in React to draw polygons on a map. Would like to fill these polygons, and also adjust the border width of the polygons. My understanding is that it is not possible to adjust the border width as a fill property, so a separate line style must be created.

The problem that I am having, is that when I attempt to add an additional style to set the line width, it does not work. Apparently what is happening is that the first style layer is the one that is rendered, and the second one is not, per the code below: "STYLE LAYERS #'S 1 AND 2." I can get the line style to render if I place it in the first position, but then I get no fill layer, and vice-versa.

Any thoughts on this?

  useEffect(() => {
    if (map.current) return;
    map.current = new mapboxgl.Map({
      container: mapContainer.current,
      style: "mapbox://styles/mapbox/streets-v11",
      center: [lng, lat],
      zoom: zoom,
    });
  });

  useEffect(() => {
    if (!map.current) return;
    map.current.on("move", () => {
      console.log(map.current.getCenter().lng.toFixed(4));
      setLng(map.current.getCenter().lng.toFixed(4));
      setLat(map.current.getCenter().lat.toFixed(4));
      setZoom(map.current.getZoom().toFixed(2));
    });
  });

  useEffect(() => {
    if (!map.current) return;
    map.current.on("load", () => {
      dataArray.map((item) => {
        map.current.addSource(item.name, {
          type: "geojson",
          data: {
            type: "Feature",
            geometry: {
              type: "Polygon",
              coordinates: item.data,
            },
            properties: {
              name: item.name,
            },
          },
        });

        //STYLE LAYER #1
        map.current.addLayer({
          id: item.name,
          type: "fill",
          source: item.name, 
          layout: {},
          paint: {
            "fill-color": "#aaa",
            "fill-opacity": 0.25,
            "fill-outline-color": "#000",
          },
        });

        //STYLE LAYER #2
        map.current.addLayer({
          id: item.name,
          type: "line",
          source: item.name, 
          layout: {},
          paint: {
            "line-color": "#000",
            "line-width": 2,
          },
        });
      });
    });

Solution

  • Each layer needs to have a unique id (see: https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/). So, you could append "-border" to the line layer id.