SphereMap
The map itself. Hosts overlays, layers and controls, and reports every map event
SphereMap creates a Sphere map in a <div> and renders its children (markers, shapes, layers, controls…) once the map is ready.
- No events yet
import { Marker, SphereMap } from "gistda-sphere-react";
<SphereMap
center={{ lon: 100.5018, lat: 13.7563 }}
zoom={10}
language="en"
style={{ height: 400 }}
onClick={({ lat, lon }) => console.log(`Clicked at ${lat}, ${lon}`)}
>
<Marker position={{ lon: 100.5018, lat: 13.7563 }} title="Bangkok" />
</SphereMap>The map fills its container, so give the map (or its parent) a height. Without one, the <div> collapses to 0 px.
Props
Props marked live update the map in place when they change. The others only set the initial state, so use the ref or useMapControls to change them later.
| Prop | Type | Default | Description |
|---|---|---|---|
center | Location | Sphere default | Initial center, { lon, lat }. |
zoom | number | 7 | Initial zoom level (0–22). |
rotate | number | 0 | Initial rotation (bearing) in degrees, clockwise from north. |
pitch | number | 0 | Initial tilt in degrees (up to 60 by default). |
language | "th" | "en" | provider's, else "th" | Live. Language of labels and built-in UI. Defaults to SphereProvider's language. |
baseLayer | LayerInput | "STREETS" | Live. Base map: a built-in layer name, a sphere.Layer, a MapLibre style URL or a style object. |
filter | FilterType | "None" | Live. Color filter: "None", "Dark", "Light", "Protanopia" or "Deuteranopia". |
zoomRange | Range | { min: 0, max: 22 } | Live. Zoom levels users can reach, { min, max }. |
controls | UiControlsConfig | – | Live. Show or hide built-in controls, e.g. { DPad: false, Scale: true }. |
ui | "Full" | "Mobile" | "None" | fits the container | Which built-in UI to create. See UI modes. |
input | boolean | true | Allow mouse, touch and keyboard input. |
lastView | boolean | false | Restore the last center and zoom from local storage. |
options | Record<string, unknown> | – | Extra options for new sphere.Map(), including any MapLibre map option. |
ref | Ref<SphereMapRef> | – | Imperative control. See Ref. |
style, className, id | – | – | Applied to the container <div>. |
children | ReactNode | – | Rendered once the map is ready. |
fallback | ReactNode | – | Shown over the map area until the map is ready, such as a spinner. See Loading placeholder. |
Events
Every Sphere map event has a callback prop. Handlers receive the values Sphere reports.
| Prop | Arguments | When |
|---|---|---|
onReady | (map) | The map is ready, and children render from here on. |
onClick | ({ lat, lon, x, y }) | The map was clicked (not fired when an overlay was clicked). |
onDoubleClick | ({ lat, lon, x, y }) | The map was double-clicked. |
onMouseMove | ({ lat, lon, x, y }) | The pointer moved over the map. |
onWheel | ({ x, y, delta }) | The mouse wheel turned. |
onZoom | (zoom) | The zoom level changed. |
onLocation | (center) | The center moved. |
onRotate | (angle) | The rotation changed. |
onPitch | (angle) | The tilt changed. |
onViewChange | ({ center, zoom, rotate, pitch, bound }) | The map is ready, or stopped moving. See Syncing the view. |
onZoomRange | ({ min, max }) | The allowed zoom range changed. |
onDrag / onDrop | () | The user started / stopped dragging the map. |
onIdle | () | The map finished rendering. |
onRepaint | () | The map was repainted. |
onResize | () | The map was resized. |
onFullscreen | (isFullscreen) | Fullscreen was turned on or off. |
onLayerChange | (added) or (undefined, removed) | A layer was added or removed. |
onTileLoading / onTileLoaded | (sourceId) | Tiles of a source started / finished loading. |
onOverlayClick | (overlay, location) | An overlay was clicked. |
onOverlayHover / onOverlayLeave | (overlay) | The pointer entered / left an overlay. |
onOverlayDrag / onOverlayDrop | (overlay) | An overlay is being dragged / was dropped. |
onOverlayChange | (overlay) | An overlay was added or removed. |
onOverlayUpdate | (overlay) | An overlay was edited. |
onOverlayLoad | (data) | A predefined overlay or object loaded. |
onPopupClose | (popup) | A popup was closed. |
onBeforeContextMenu | ({ location, add }) | The right-click menu is about to open. Call add(element) to add items, or return false to cancel it. |
onContextMenu | () | The right-click menu opened. |
onRouteComplete | (routes) | A route finished calculating. Prefer useRoute. |
onRouteError | (status) | Routing failed. |
onToolbarChange | (mode) | The drawing toolbar changed mode. |
onDrawCreate / onDrawDelete | (features) | Shapes were drawn / deleted with the built-in toolbar. |
onTooltipChange | (message) | The toolbar's tooltip text changed. |
onError | (error: Error) | The map reported an error. |
To listen from a child component instead, use useMapEvent.
Base maps and filters
import { SphereMap } from "gistda-sphere-react";
import { useState } from "react";
const [dark, setDark] = useState(false);
<SphereMap baseLayer="HYBRID" filter={dark ? "Dark" : "None"} />Built-in base layers are "SIMPLE", "STREETS", "STREETS_NIGHT", "HYBRID" and "IMAGES". baseLayer also accepts a MapLibre style, such as Sphere's own vector styles:
import { SphereMap } from "gistda-sphere-react";
<SphereMap baseLayer="https://basemap.sphere.gistda.or.th/vector/sphere_hybrid.json" />Built-in controls
import { SphereMap } from "gistda-sphere-react";
<SphereMap controls={{ DPad: false, Zoombar: true, Scale: true, LayerSelector: false }} />| Control | Description |
|---|---|
DPad | Arrows for panning. |
Zoombar | Zoom in/out buttons. |
Geolocation | Jump to the user's location. |
Toolbar | Drawing and measuring tools (desktop UI only). |
LayerSelector | Base map and layer menu. |
Fullscreen | Fullscreen toggle (desktop UI only). |
Crosshair | A crosshair at the center. |
Scale | Scale bar. |
ContextMenu | Right-click menu. |
For input, lock and context-menu settings, see useUi. To add your own controls, see MapControl and MenuBar.
UI modes
ui | Description |
|---|---|
"Full" | Desktop controls: zoom bar, D-pad, geolocation, toolbar, layer menu, fullscreen and scale. |
"Mobile" | Compact controls for small screens (no toolbar). |
"None" | No built-in UI. |
Without ui, Sphere picks the mobile UI when the map is narrower than 600 px.
MapLibre options
options is passed to new sphere.Map(), and Sphere passes it on to MapLibre. Use it for anything MapLibre supports:
import { SphereMap } from "gistda-sphere-react";
<SphereMap
options={{
maxPitch: 85, // allow steeper tilts
hash: true, // keep the view in the URL
doubleClickZoom: false,
}}
/>Loading placeholder
The map appears once Sphere's script has loaded and the map is ready. Until then, fallback covers the map area:
import { SphereMap } from "gistda-sphere-react";
<SphereMap
fallback={<div className="grid h-full place-items-center">Loading map…</div>}
style={{ height: 400 }}
/>fallback stays up if the script can't load. To show an error instead, read error from useSphere.
Syncing the view
onViewChange reports the view when the map is ready and each time it stops moving, so it suits saving the view to the URL or your state:
import { type MapView, SphereMap } from "gistda-sphere-react";
function MapWithUrl() {
const save = ({ center, zoom }: MapView) => {
const params = new URLSearchParams({
lat: center.lat.toFixed(5),
lon: center.lon.toFixed(5),
zoom: zoom.toFixed(2),
});
history.replaceState(null, "", `?${params}`);
};
return <SphereMap onViewChange={save} style={{ height: 400 }} />;
}The view has center, zoom, rotate, pitch and bound (the visible box). To read it elsewhere, use useMapView or getView() from useMapControls. onLocation and onZoom fire on every animation frame instead.
Ref
The ref gives you every useMapControls method plus getMap():
import { SphereMap, type SphereMapRef } from "gistda-sphere-react";
import { useRef } from "react";
const mapRef = useRef<SphereMapRef>(null);
<SphereMap ref={mapRef} />
mapRef.current?.goTo({ center: { lon: 98.98, lat: 18.79 }, zoom: 12 });
mapRef.current?.setRotate(45);
const sphereMap = mapRef.current?.getMap(); // the sphere.Map instance
const maplibre = sphereMap?.Renderer; // the MapLibre map| Method | Description |
|---|---|
getMap() | The underlying sphere.Map, or null. Its Renderer is the MapLibre map. |
getView() | Center, zoom, rotation, tilt and visible box in one object. |
goTo(options, animate?) | Fly or jump to a view (center, zoom, rotate or bearing, pitch, padding, duration). |
setCenter / getCenter | Center of the map. |
setZoom / getZoom, zoomIn, zoomOut | Zoom level. |
setRotate / getRotate | Rotation in degrees. |
setPitch / getPitch | Tilt in degrees. |
setBound(bound, options?) / getBound | Fit to or read the visible area. |
panBy({ x, y }) | Pan by pixels. |
setZoomRange / getZoomRange | Allowed zoom levels. |
setBaseLayer, addLayer, removeLayer, clearLayers, getLayers | Layers. |
setFilter / getFilter | Color filter. |
setLanguage / getLanguage | Map language. |
loadPredefinedOverlay / unloadPredefinedOverlay | Live overlays (cameras, events, AQI). |
repaint, resize | Redraw, or re-measure after the container changes size. |
Changing center, zoom, rotate or pitch props after the first render has no effect. Move the map with the ref or useMapControls, so user panning is never overwritten by a re-render. To keep your state in step with the map, use onViewChange.