gistda-sphere-react

Drawing polygons

Click to add corners, double-click to finish

Click to add corners, then double-click (or press Finish) to complete the polygon:

Click to add corners, then double-click or press Finish.0 drawn

With hooks instead

The demo keeps its shapes in component state. To keep them in a hook instead, and listen to clicks from a child component of the map, use usePolygons and useMapEvent:

import { useState } from "react";
import {
  Dot, Polygon, SphereMap, SphereProvider,
  useMapEvent, usePolygons, type Location,
} from "gistda-sphere-react";

/** Drops repeated points: the two clicks of a double-click land on the same spot. */
const withoutRepeats = (points: Location[]) =>
  points.filter(
    (point, index) =>
      index === 0 || point.lat !== points[index - 1].lat || point.lon !== points[index - 1].lon
  );

function PolygonDrawer() {
  const [points, setPoints] = useState<Location[]>([]);
  const { items: polygons, add } = usePolygons();

  useMapEvent("click", ({ lat, lon }) => {
    setPoints((previous) => [...previous, { lat, lon }]);
  });

  useMapEvent("doubleClick", () => {
    const corners = withoutRepeats(points);
    if (corners.length >= 3) {
      add({ positions: corners, fillColor: "rgba(255,0,0,0.3)", lineColor: "red" });
      setPoints([]);
    }
  });

  return (
    <>
      {polygons.map(({ id, ...polygon }) => (
        <Polygon key={id} {...polygon} />
      ))}
      {points.map((point, index) => (
        <Dot key={index} position={point} lineColor="red" lineWidth={8} />
      ))}
    </>
  );
}

function App() {
  return (
    <SphereProvider apiKey="YOUR_API_KEY">
      <SphereMap
        center={{ lon: 100.5, lat: 13.75 }}
        zoom={10}
        style={{ height: 500 }}
        options={{ doubleClickZoom: false }}
      >
        <PolygonDrawer />
      </SphereMap>
    </SphereProvider>
  );
}

Tips

  • A double-click also sends two clicks. Drop repeated points before finishing, as above.
  • options={{ doubleClickZoom: false }} stops double-clicks from zooming the map. Pass it only while drawing if you want zooming the rest of the time.
  • Sphere also has a built-in drawing toolbar: show it with controls={{ Toolbar: true }} and receive the shapes from onDrawCreate.
  • The playground has a complete drawing tool with lines, circles, rectangles, measurements and spatial analysis.

On this page