Event hooks
Listen to any map event from a component, with typed arguments
Event hooks subscribe a component to map events and unsubscribe when it unmounts. They work inside SphereMap and anywhere else under SphereProvider, and the handler always sees your latest props and state.
- No events yet
useMapEvent
import { useMapEvent } from "gistda-sphere-react";
function ClickLogger() {
useMapEvent("click", ({ lat, lon }) => {
console.log(`Clicked at ${lat}, ${lon}`);
});
useMapEvent("overlayClick", (overlay, location) => {
console.log("Overlay clicked at", location);
});
return null;
}The handler's arguments are typed per event (see SphereEventMap). The event names and what they pass are listed on the SphereMap events table, for example click ↔ onClick.
Cancelling the context menu
Handlers can return false to cancel cancellable events. Use it with beforeContextmenu to add your own menu items or hide the menu:
import { useMapEvent } from "gistda-sphere-react";
useMapEvent("beforeContextmenu", (menu) => {
const item = document.createElement("button");
item.textContent = "Add a stop here";
item.onclick = () => addStop(menu.location);
menu.add(item);
});Shortcuts
| Hook | Handler | Notes |
|---|---|---|
useMapReady(handler) | (map) => void | Runs once the map is ready, or right away if it already is. |
useMapClick(handler) | ({ lat, lon, x, y }) => void | Map clicks (not fired for clicks on overlays). |
useMapZoom(handler) | (zoom) => void | Zoom changes, with the new level. Fires on every animation frame. |
useMapLocation(handler) | (center) => void | Center changes, with the new { lon, lat }. Fires on every animation frame. |
useOverlayClick(handler) | ({ overlay, location }) => void | Clicks on any overlay. |
import { useMapReady, useMapZoom } from "gistda-sphere-react";
import { useState } from "react";
function ZoomIndicator() {
const [zoom, setZoom] = useState<number | null>(null);
useMapReady((map) => setZoom(map.zoom()));
useMapZoom(setZoom);
return <span>Zoom {zoom?.toFixed(1)}</span>;
}Events like mousemove, zoom, location and repaint fire many times per second while the map moves. Avoid heavy work in their handlers, or batch updates with requestAnimationFrame.
useMapView
useMapView returns the current view and updates it when the map stops moving, which suits readouts and saving the view. It returns null until the map is ready.
import { useMapView } from "gistda-sphere-react";
function ViewReadout() {
const view = useMapView();
if (!view) return null;
const { center, zoom } = view;
return (
<p>
{center.lat.toFixed(4)}, {center.lon.toFixed(4)} at zoom {zoom.toFixed(1)}
</p>
);
}The view has center, zoom, rotate, pitch and bound (the visible box). For updates on every animation frame, use useMapZoom and useMapLocation instead.
Event props or event hooks?
Both receive the same events. Use SphereMap's on… props when the map's owner handles the event, and event hooks when a child or a sidebar component cares about it.