Search code examples
reactjsnext.jsreact-map-gl

drawing a radius circle on react-map-gl map


I am currently working with react-map-gl and need to set a marker with an range circle around it.

I can set the marker by importing Marker from react-map-gl.

But i am stuck on the radius which should be based on km around the marker.

Does anyone have a solution for this?


Solution

  • I figured out a solution to draw a radius.

    import circle from '@turf/circle';
    import MapGL, { ScaleControl, useMap, Marker, Source, Layer } from "react-map-gl";
    
    export function Map({ range, coordinates }) {
      const center = [coordinates.lng, coordinates.lat];
      const radius = range ?? 30; // set fallback to 30 Kilometer
    
      const circleData = useMemo(() => {
        const options = { steps: 64, units: 'kilometers' };
        const myCircle = circle(center, radius, options);
        return myCircle;
      }, [center, radius]);
    
      return (
        <MapGL>
          <Source id="circle-source" type="geojson" data={circleData}>
            <Layer
             id="circle-layer"
             type="fill"
             paint={{
              'fill-color': '#888',
              'fill-opacity': 0.4,
             }}
            />
          </Source>
        </MapGL> 
      )
    }