Search code examples
polygonhighlightreact-map-gl

react-map-gl add background color outside polygon


I am using react-map-gl and I want to somewhat put a background color outside the polygon that was created. I tried using multiple <Layers /> but it looks like it does not accept multiple instances.

<Source id="polygons-source" type="geojson" data={geojsonData}>
  <Layer
    id="polygons"
    type="line"
    source="polygons-source"
    paint={{ 
      'line-color': 'red', 
      'line-opacity': 1, 
      'line-width': 1
    }}
  />
  <Layer
    id="polygons"
    type="fill"
    source="polygons-source"
    paint={{ 
      'fill-color': 'transparent',
      'fill-opacity': 0.5
    }}
  />
  <Layer
    id="polygons"
    type="background"
    source="polygons-source"
    paint={{ 
      'background-color': 'gray', 
      'background-opacity': 0.5
    }}
  />
</Source>

It just show me the first instance of the <Layer /> component


Solution

  • First, about the layer question, you need to have different id for them to appear. you can also stack them to different orders: using the beforeId property of the <Layer> component.

    Second, to highlight only the polygon you can use the mask function from @turf/turf package.

    import * as turf from '@turf/turf';
    
    const poly = turf.polygon(geojsonData.features[0].geometry.coordinates);
    const worldMask= turf.polygon([
      [
        [-180, -90],
        [180, -90],
        [180, 90],
        [-180, 90],
        [-180, -90],
      ],
    ]);
    
    var masked = turf.mask(poly, mask);
    
    <Source id="polygons-source" type="geojson" data={masked}>
        <Layer
          id="polygons"
          type="fill"
          source="polygons-source"
          paint={{ 'fill-color': 'gray', 'fill-opacity': 0.5 }}
        />
    </Source>