Draw a radius

Estimated reading time: 1 minute

Use the code sample below to draw a location radius using a polygon. This example uses the Turf.js library to generate a circle as a polygon

View on GitHub

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8" />
    <link href="https://unpkg.com/[email protected]/dist/maplibre-gl.css" rel="stylesheet" />
    <script src="https://unpkg.com/[email protected]/dist/maplibre-gl.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@turf/turf@7/turf.min.js"></script>
    <style>
      html,
      body {
        margin: 0;
        padding: 0;
        height: 100%;
      }
      #map {
        min-height: 500px;
        height: 100%;
        width: 100%;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>
      // Don't forget to replace <YOUR_ACCESS_TOKEN> by your own access token
      const accessToken = "<YOUR_ACCESS_TOKEN>";
      const radiusCenter = [2.3454, 48.8452];
      const map = new maplibregl.Map({
        container: "map",
        style: `https://api.jawg.io/styles/jawg-streets.json?access-token=${accessToken}`,
        zoom: 13,
        center: radiusCenter,
        hash: true,
      }).addControl(new maplibregl.NavigationControl(), "top-right");
      // This plugin is used for right to left languages
      maplibregl.setRTLTextPlugin("https://unpkg.com/@mapbox/[email protected]/mapbox-gl-rtl-text.min.js");

      map.on("load", () => {
        // Generate a polygon using turf.circle.
        // See https://turfjs.org/docs/api/circle
        const radius = 1; // kilometer
        const options = {
          steps: 64,
          units: "kilometers",
        };
        const circle = turf.circle(radiusCenter, radius, options);

        // Add the circle as a GeoJSON source
        map.addSource("location-radius", {
          type: "geojson",
          data: circle,
        });

        // Add a fill layer with some transparency
        map.addLayer({
          id: "location-radius",
          type: "fill",
          source: "location-radius",
          paint: {
            "fill-color": "#8CCFFF",
            "fill-opacity": 0.5,
          },
        });

        // Add a line layer to draw the circle outline
        map.addLayer({
          id: "location-radius-outline",
          type: "line",
          source: "location-radius",
          paint: {
            "line-color": "#0094ff",
            "line-width": 3,
          },
        });
      });
    </script>
  </body>
</html>