Globe
import { Globe, useDrag, useGlobeZoomHandler, useTour } from '@dxos/react-ui-geo';import { loadTopology } from '@dxos/react-ui-geo/data';npm install @dxos/react-ui-geoGlobe is a globe of countries drawn on a canvas. It draws the outlines from data in the package, so it needs no tile
server, works offline and sends no requests to a third party. For a street map, use
Map.
Add the package’s strings from @dxos/react-ui-geo/translations to the resourceExtensions of Theme.Provider.
| Part | What it is |
|---|---|
Globe.Root |
The root, which holds the center, zoom, rotation and translation. Its ref gives a GlobeController |
Globe.Viewport |
The frame that measures its space and sizes the canvas to it |
Globe.Canvas |
The canvas, which draws the topology and the features. The features are points and the lines between them |
Globe.Zoom |
The zoom in and zoom out buttons |
Globe.Action |
The start and toggle buttons, for a spin or a tour |
Globe.Panel |
A panel at a corner of the viewport |
Globe.Debug |
The globe’s state, for development |
The hooks act on the controller:
useDragturns the globe as the user drags.useWheelzooms with the wheel.useSpinnerturns the globe on its own.useTourflies from point to point.useGlobeZoomHandlerconnects the zoom buttons.
Globe.Canvas
Section titled “Globe.Canvas”Globe.Canvas draws the country outlines, and the points and lines you pass as features.
| Prop | Type | Effect |
|---|---|---|
topology |
Topology |
Sets the country outlines, from loadTopology. 110m is the smallest |
features |
{ points, lines, selected } |
Sets the places, as lat and lng, and the lines from a source to a target. selected places draw above the rest |
projection |
'orthographic' | 'mercator' | 'transverse-mercator' | 'equirectangular' | GeoProjection |
Sets the projection, by name or as a d3 projection. 'orthographic', a globe, by default |
fit |
'contain' | 'cover' |
Sets how the whole sphere sits in the canvas at zoom 1. The projection’s own scale by default |
styles |
StyleSet |
Sets the colors for each layer. The theme’s colors by default |
A trip on a globe
Section titled “A trip on a globe”useTour flies from point to point and draws the arc it travels. It returns whether the tour is running, and a
setter that starts or stops it. The tour stops by itself after one pass over the points. With loop, the pass ends
back at the first point.
Example (Flying a trip around the world, lap after lap)
import { function useEffect(effect: React.EffectCallback, deps?: React.DependencyList): void
Accepts a function that contains imperative, possibly effectful code.
useEffect, function useState<S>(initialState: S | (() => S)): [S, React.Dispatch<React.SetStateAction<S>>] (+1 overload)
Returns a stateful value, and a function to update it.
useState } from 'react';import { const Globe: { Root: React.ForwardRefExoticComponent<Partial<Pick<GlobeContextType, "center" | "rotation" | "translation" | "zoom">> & { children?: React.ReactNode | undefined; } & React.RefAttributes<GlobeController>>; Viewport: React.ForwardRefExoticComponent<Omit<{}, "className"> & { classNames?: import("@dxos/ui-types").ClassNameValue; } & Pick<React.HTMLAttributes<Element>, "children" | "role" | "style"> & React.RefAttributes<HTMLDivElement>>; Canvas: { ({ projection: projectionProp, fit, topology, features, styles: stylesProp }: GlobeCanvasProps): React.JSX.Element; displayName: string; }; Zoom: ({ onAction, position, ...props }: GlobeControlProps) => React.JSX.Element; Action: ({ onAction, position, ...props }: GlobeControlProps) => React.JSX.Element; Debug: ({ position }: { position?: ControlPosition; }) => React.JSX.Element; Panel: ({ position, classNames, children, }: ThemedClassName<React.PropsWithChildren & { position?: ControlPosition; }>) => React.JSX.Element;}
Globe, type type GlobeController = { canvas: HTMLCanvasElement; projection: GeoProjection; flyTo: (target: FlyToTarget, options?: FlyToOptions) => Promise<void>; cancelFlyTo: () => void;} & Pick<GlobeContextType, "rotation" | "translation" | "zoom" | "setZoom" | "setTranslation" | "setRotation">
GlobeController, type type StyleSet = { background?: Styles | undefined; water?: Styles | undefined; graticule?: Styles | undefined; land?: Styles | undefined; border?: Styles | undefined; dots?: Styles | undefined; point?: Styles | undefined; selected?: Styles | undefined; line?: Styles | undefined; cursor?: Styles | undefined; arc?: Styles | undefined;}
StyleSet, const useDrag: (controller?: GlobeController | null, options?: DragOptions) => void
Allows user to drag globe.
useDrag, const useGlobeZoomHandler: (controller: GlobeController | null | undefined) => ControlProps["onAction"]
useGlobeZoomHandler, const useTour: (controller?: GlobeController | null, points?: LatLngLiteral[], options?: TourOptions) => [boolean, React.Dispatch<React.SetStateAction<boolean>>]
Iterates between points by chaining controller.flyTo calls, rendering
an arc + cursor on the canvas per frame via the flyTo onTick hook.
Inspired by: https://observablehq.com/@mbostock/top-100-cities
useTour } from '@dxos/react-ui-geo';import { const loadTopology: (resolution?: CountriesResolution) => Promise<Topology>
loadTopology } from '@dxos/react-ui-geo/data';import * as import Hooks
Hooks from '@dxos/react-ui/Hooks';
/** A trip around the world: London, New York, Tokyo, Sydney, São Paulo and back to London. */const const TRIP: { lat: number; lng: number;}[]
A trip around the world: London, New York, Tokyo, Sydney, São Paulo and back to London.
TRIP = [ { lat: number
lat: 51.5074, lng: number
lng: -0.1278 }, { lat: number
lat: 40.7128, lng: number
lng: -74.006 }, { lat: number
lat: 35.6762, lng: number
lng: 139.6503 }, { lat: number
lat: -33.8688, lng: number
lng: 151.2093 }, { lat: number
lat: -23.5505, lng: number
lng: -46.6333 },];
const const LEGS: { source: { lat: number; lng: number; }; target: { lat: number; lng: number; };}[]
LEGS = const TRIP: { lat: number; lng: number;}[]
A trip around the world: London, New York, Tokyo, Sydney, São Paulo and back to London.
TRIP.Array<{ lat: number; lng: number; }>.map<{ source: { lat: number; lng: number; }; target: { lat: number; lng: number; };}>(callbackfn: (value: { lat: number; lng: number;}, index: number, array: { lat: number; lng: number;}[]) => { source: { lat: number; lng: number; }; target: { lat: number; lng: number; };}, thisArg?: any): { source: { lat: number; lng: number; }; target: { lat: number; lng: number; };}[]
Calls a defined callback function on each element of an array, and returns an array that contains the results.
map((source: { lat: number; lng: number;}
source, index: number
index) => ({ source: { lat: number; lng: number;}
source, target: { lat: number; lng: number;}
target: const TRIP: { lat: number; lng: number;}[]
A trip around the world: London, New York, Tokyo, Sydney, São Paulo and back to London.
TRIP[(index: number
index + 1) % const TRIP: { lat: number; lng: number;}[]
A trip around the world: London, New York, Tokyo, Sydney, São Paulo and back to London.
TRIP.Array<{ lat: number; lng: number; }>.length: number
Gets or sets the length of the array. This is a number one higher than the highest index in the array.
length],}));
const const STYLES: Record<"light" | "dark", Partial<Record<Style, Styles>>>
STYLES: type Record<K extends keyof any, T> = { [P in K]: T; }
Construct a type with a set of properties K of type T
Record<'light' | 'dark', type StyleSet = { background?: Styles | undefined; water?: Styles | undefined; graticule?: Styles | undefined; land?: Styles | undefined; border?: Styles | undefined; dots?: Styles | undefined; point?: Styles | undefined; selected?: Styles | undefined; line?: Styles | undefined; cursor?: Styles | undefined; arc?: Styles | undefined;}
StyleSet> = { light: Partial<Record<Style, Styles>>
light: { background?: Styles | undefined
background: { fillStyle: string
fillStyle: '#EEE' }, water?: Styles | undefined
water: { fillStyle: string
fillStyle: '#555' }, land?: Styles | undefined
land: { fillStyle: string
fillStyle: '#999' }, line?: Styles | undefined
line: { strokeStyle: string
strokeStyle: '#b91c1c', lineWidth: number
lineWidth: 1, lineDash: number[]
lineDash: [4, 6] }, point?: Styles | undefined
point: { fillStyle: string
fillStyle: '#b91c1c', pointRadius: number
pointRadius: 3 }, arc?: Styles | undefined
arc: { strokeStyle: string
strokeStyle: '#f97316', lineWidth: number
lineWidth: 2 }, cursor?: Styles | undefined
cursor: { fillStyle: string
fillStyle: '#f97316', pointRadius: number
pointRadius: 3 }, }, dark: Partial<Record<Style, Styles>>
dark: { background?: Styles | undefined
background: { fillStyle: string
fillStyle: '#111' }, water?: Styles | undefined
water: { fillStyle: string
fillStyle: '#123E6A' }, land?: Styles | undefined
land: { fillStyle: string
fillStyle: '#032153' }, line?: Styles | undefined
line: { strokeStyle: string
strokeStyle: '#fbbf24', lineWidth: number
lineWidth: 1, lineDash: number[]
lineDash: [4, 6] }, point?: Styles | undefined
point: { fillStyle: string
fillStyle: '#f87171', pointRadius: number
pointRadius: 3 }, arc?: Styles | undefined
arc: { strokeStyle: string
strokeStyle: '#fbbf24', lineWidth: number
lineWidth: 2 }, cursor?: Styles | undefined
cursor: { fillStyle: string
fillStyle: '#fbbf24', pointRadius: number
pointRadius: 3 }, },};
/** The globe flies from stop to stop along the trip, over and over; drag it to take over, and the tour resumes after. */export const const TripGlobe: () => React.JSX.Element
The globe flies from stop to stop along the trip, over and over; drag it to take over, and the tour resumes after.
TripGlobe = () => { const const themeMode: ThemeMode
themeMode = import Hooks
Hooks.const useThemeMode: () => ThemeMode
The ThemeProvider's light or dark mode.
useThemeMode(); // The country outlines load on demand, so the globe draws once they arrive. const [const topology: Topology<Objects<GeoJsonProperties>> | undefined
topology] = import Hooks
Hooks.useAsyncState<Topology<Objects<GeoJsonProperties>>>(cb: () => Promise<Topology<Objects<GeoJsonProperties>> | undefined>, deps?: any[]): [Topology<Objects<GeoJsonProperties>> | undefined, React.Dispatch<React.SetStateAction<Topology<Objects<GeoJsonProperties>> | undefined>>]export useAsyncState
NOTE: Use with care and when necessary to be able to cancel an async operation when unmounting.
useAsyncState(() => function loadTopology(resolution?: CountriesResolution): Promise<Topology>
loadTopology('110m'), []); const [const controller: GlobeController | null
controller, const setController: React.Dispatch<React.SetStateAction<GlobeController | null>>
setController] = useState<GlobeController | null>(initialState: GlobeController | (() => GlobeController | null) | null): [GlobeController | null, React.Dispatch<React.SetStateAction<GlobeController | null>>] (+1 overload)
Returns a stateful value, and a function to update it.
useState<type GlobeController = { canvas: HTMLCanvasElement; projection: GeoProjection; flyTo: (target: FlyToTarget, options?: FlyToOptions) => Promise<void>; cancelFlyTo: () => void;} & Pick<GlobeContextType, "rotation" | "translation" | "zoom" | "setZoom" | "setTranslation" | "setRotation">
GlobeController | null>(null); const [const dragging: boolean
dragging, const setDragging: React.Dispatch<React.SetStateAction<boolean>>
setDragging] = useState<boolean>(initialState: boolean | (() => boolean)): [boolean, React.Dispatch<React.SetStateAction<boolean>>] (+1 overload)
Returns a stateful value, and a function to update it.
useState(false); const const handleZoom: ((action: ControlAction) => void) | undefined
handleZoom = function useGlobeZoomHandler(controller: GlobeController | null | undefined): ControlProps["onAction"]
useGlobeZoomHandler(const controller: GlobeController | null
controller); const const styles: Partial<Record<Style, Styles>>
styles = const STYLES: Record<"light" | "dark", Partial<Record<Style, Styles>>>
STYLES[const themeMode: ThemeMode
themeMode]; const [const running: boolean
running, const setRunning: React.Dispatch<React.SetStateAction<boolean>>
setRunning] = function useTour(controller?: GlobeController | null, points?: LatLngLiteral[], options?: TourOptions): [boolean, React.Dispatch<React.SetStateAction<boolean>>]
Iterates between points by chaining controller.flyTo calls, rendering
an arc + cursor on the canvas per frame via the flyTo onTick hook.
Inspired by: https://observablehq.com/@mbostock/top-100-cities
useTour(const controller: GlobeController | null
controller, const TRIP: { lat: number; lng: number;}[]
A trip around the world: London, New York, Tokyo, Sydney, São Paulo and back to London.
TRIP, { loop?: boolean | undefined
loop: true, duration?: number | undefined
duration: 2_000, styles?: Partial<Record<Style, Styles>> | undefined
styles, }); function useDrag(controller?: GlobeController | null, options?: DragOptions): void
Allows user to drag globe.
useDrag(const controller: GlobeController | null
controller, { onUpdate?: ((event: GlobeDragEvent) => void) | undefined
onUpdate: ({ type: "start" | "move" | "end"
type }) => { const setDragging: (value: React.SetStateAction<boolean>) => void
setDragging(type: "start" | "move" | "end"
type !== 'end'); if (type: "start" | "move" | "end"
type === 'start') { const setRunning: (value: React.SetStateAction<boolean>) => void
setRunning(false); } }, });
// Start a lap once the canvas is mounted, and again after a pause when a lap ends or the user lets go. function useEffect(effect: React.EffectCallback, deps?: React.DependencyList): void
Accepts a function that contains imperative, possibly effectful code.
useEffect(() => { if (const running: boolean
running || const dragging: boolean
dragging || !const controller: GlobeController | null
controller?.canvas: HTMLCanvasElement | undefined
canvas) { return; } const const timeout: number
timeout = function setTimeout(handler: TimerHandler, timeout?: number, ...arguments: any[]): number
setTimeout(() => const setRunning: (value: React.SetStateAction<boolean>) => void
setRunning(true), 1_500); return () => function clearTimeout(id: number | undefined): void
clearTimeout(const timeout: number
timeout); }, [const controller: GlobeController | null
controller, const running: boolean
running, const dragging: boolean
dragging]);
return ( <const Globe: { Root: React.ForwardRefExoticComponent<Partial<Pick<GlobeContextType, "center" | "rotation" | "translation" | "zoom">> & { children?: React.ReactNode | undefined; } & React.RefAttributes<GlobeController>>; Viewport: React.ForwardRefExoticComponent<Omit<{}, "className"> & { classNames?: import("@dxos/ui-types").ClassNameValue; } & Pick<React.HTMLAttributes<Element>, "children" | "role" | "style"> & React.RefAttributes<HTMLDivElement>>; Canvas: { ({ projection: projectionProp, fit, topology, features, styles: stylesProp }: GlobeCanvasProps): React.JSX.Element; displayName: string; }; Zoom: ({ onAction, position, ...props }: GlobeControlProps) => React.JSX.Element; Action: ({ onAction, position, ...props }: GlobeControlProps) => React.JSX.Element; Debug: ({ position }: { position?: ControlPosition; }) => React.JSX.Element; Panel: ({ position, classNames, children, }: ThemedClassName<React.PropsWithChildren & { position?: ControlPosition; }>) => React.JSX.Element;}
Globe.type Root: React.ForwardRefExoticComponent<Partial<Pick<GlobeContextType, "center" | "rotation" | "translation" | "zoom">> & { children?: React.ReactNode | undefined;} & React.RefAttributes<GlobeController>>
Root zoom?: number | undefined
zoom={1.1} rotation?: Vector | undefined
rotation={[0, -20, 0]} RefAttributes<GlobeController>.ref?: React.Ref<GlobeController> | undefined
Allows getting a ref to the component instance.
Once the component unmounts, React will set ref.current to null
(or call the ref with null if you passed a callback ref).
ref={const setController: React.Dispatch<React.SetStateAction<GlobeController | null>>
setController}> <const Globe: { Root: React.ForwardRefExoticComponent<Partial<Pick<GlobeContextType, "center" | "rotation" | "translation" | "zoom">> & { children?: React.ReactNode | undefined; } & React.RefAttributes<GlobeController>>; Viewport: React.ForwardRefExoticComponent<Omit<{}, "className"> & { classNames?: import("@dxos/ui-types").ClassNameValue; } & Pick<React.HTMLAttributes<Element>, "children" | "role" | "style"> & React.RefAttributes<HTMLDivElement>>; Canvas: { ({ projection: projectionProp, fit, topology, features, styles: stylesProp }: GlobeCanvasProps): React.JSX.Element; displayName: string; }; Zoom: ({ onAction, position, ...props }: GlobeControlProps) => React.JSX.Element; Action: ({ onAction, position, ...props }: GlobeControlProps) => React.JSX.Element; Debug: ({ position }: { position?: ControlPosition; }) => React.JSX.Element; Panel: ({ position, classNames, children, }: ThemedClassName<React.PropsWithChildren & { position?: ControlPosition; }>) => React.JSX.Element;}
Globe.type Viewport: React.ForwardRefExoticComponent<Omit<{}, "className"> & { classNames?: import("@dxos/ui-types").ClassNameValue;} & Pick<React.HTMLAttributes<Element>, "children" | "role" | "style"> & React.RefAttributes<HTMLDivElement>>
Viewport> <const Globe: { Root: React.ForwardRefExoticComponent<Partial<Pick<GlobeContextType, "center" | "rotation" | "translation" | "zoom">> & { children?: React.ReactNode | undefined; } & React.RefAttributes<GlobeController>>; Viewport: React.ForwardRefExoticComponent<Omit<{}, "className"> & { classNames?: import("@dxos/ui-types").ClassNameValue; } & Pick<React.HTMLAttributes<Element>, "children" | "role" | "style"> & React.RefAttributes<HTMLDivElement>>; Canvas: { ({ projection: projectionProp, fit, topology, features, styles: stylesProp }: GlobeCanvasProps): React.JSX.Element; displayName: string; }; Zoom: ({ onAction, position, ...props }: GlobeControlProps) => React.JSX.Element; Action: ({ onAction, position, ...props }: GlobeControlProps) => React.JSX.Element; Debug: ({ position }: { position?: ControlPosition; }) => React.JSX.Element; Panel: ({ position, classNames, children, }: ThemedClassName<React.PropsWithChildren & { position?: ControlPosition; }>) => React.JSX.Element;}
Globe.type Canvas: { ({ projection: projectionProp, fit, topology, features, styles: stylesProp }: GlobeCanvasProps): React.JSX.Element; displayName: string;}
Canvas topology?: Topology<Objects<GeoJsonProperties>> | undefined
topology={const topology: Topology<Objects<GeoJsonProperties>> | undefined
topology} styles?: Partial<Record<Style, Styles>> | undefined
styles={const styles: Partial<Record<Style, Styles>>
styles} features?: Features | undefined
features={{ points?: LatLngLiteral[] | undefined
points: const TRIP: { lat: number; lng: number;}[]
A trip around the world: London, New York, Tokyo, Sydney, São Paulo and back to London.
TRIP, lines?: { source: LatLngLiteral; target: LatLngLiteral;}[] | undefined
lines: const LEGS: { source: { lat: number; lng: number; }; target: { lat: number; lng: number; };}[]
LEGS }} /> <const Globe: { Root: React.ForwardRefExoticComponent<Partial<Pick<GlobeContextType, "center" | "rotation" | "translation" | "zoom">> & { children?: React.ReactNode | undefined; } & React.RefAttributes<GlobeController>>; Viewport: React.ForwardRefExoticComponent<Omit<{}, "className"> & { classNames?: import("@dxos/ui-types").ClassNameValue; } & Pick<React.HTMLAttributes<Element>, "children" | "role" | "style"> & React.RefAttributes<HTMLDivElement>>; Canvas: { ({ projection: projectionProp, fit, topology, features, styles: stylesProp }: GlobeCanvasProps): React.JSX.Element; displayName: string; }; Zoom: ({ onAction, position, ...props }: GlobeControlProps) => React.JSX.Element; Action: ({ onAction, position, ...props }: GlobeControlProps) => React.JSX.Element; Debug: ({ position }: { position?: ControlPosition; }) => React.JSX.Element; Panel: ({ position, classNames, children, }: ThemedClassName<React.PropsWithChildren & { position?: ControlPosition; }>) => React.JSX.Element;}
Globe.type Zoom: ({ onAction, position, ...props }: GlobeControlProps) => React.JSX.Element
Zoom onAction?: ((action: ControlAction) => void) | undefined
onAction={const handleZoom: ((action: ControlAction) => void) | undefined
handleZoom} /> </const Globe: { Root: React.ForwardRefExoticComponent<Partial<Pick<GlobeContextType, "center" | "rotation" | "translation" | "zoom">> & { children?: React.ReactNode | undefined; } & React.RefAttributes<GlobeController>>; Viewport: React.ForwardRefExoticComponent<Omit<{}, "className"> & { classNames?: import("@dxos/ui-types").ClassNameValue; } & Pick<React.HTMLAttributes<Element>, "children" | "role" | "style"> & React.RefAttributes<HTMLDivElement>>; Canvas: { ({ projection: projectionProp, fit, topology, features, styles: stylesProp }: GlobeCanvasProps): React.JSX.Element; displayName: string; }; Zoom: ({ onAction, position, ...props }: GlobeControlProps) => React.JSX.Element; Action: ({ onAction, position, ...props }: GlobeControlProps) => React.JSX.Element; Debug: ({ position }: { position?: ControlPosition; }) => React.JSX.Element; Panel: ({ position, classNames, children, }: ThemedClassName<React.PropsWithChildren & { position?: ControlPosition; }>) => React.JSX.Element;}
Globe.type Viewport: React.ForwardRefExoticComponent<Omit<{}, "className"> & { classNames?: import("@dxos/ui-types").ClassNameValue;} & Pick<React.HTMLAttributes<Element>, "children" | "role" | "style"> & React.RefAttributes<HTMLDivElement>>
Viewport> </const Globe: { Root: React.ForwardRefExoticComponent<Partial<Pick<GlobeContextType, "center" | "rotation" | "translation" | "zoom">> & { children?: React.ReactNode | undefined; } & React.RefAttributes<GlobeController>>; Viewport: React.ForwardRefExoticComponent<Omit<{}, "className"> & { classNames?: import("@dxos/ui-types").ClassNameValue; } & Pick<React.HTMLAttributes<Element>, "children" | "role" | "style"> & React.RefAttributes<HTMLDivElement>>; Canvas: { ({ projection: projectionProp, fit, topology, features, styles: stylesProp }: GlobeCanvasProps): React.JSX.Element; displayName: string; }; Zoom: ({ onAction, position, ...props }: GlobeControlProps) => React.JSX.Element; Action: ({ onAction, position, ...props }: GlobeControlProps) => React.JSX.Element; Debug: ({ position }: { position?: ControlPosition; }) => React.JSX.Element; Panel: ({ position, classNames, children, }: ThemedClassName<React.PropsWithChildren & { position?: ControlPosition; }>) => React.JSX.Element;}
Globe.type Root: React.ForwardRefExoticComponent<Partial<Pick<GlobeContextType, "center" | "rotation" | "translation" | "zoom">> & { children?: React.ReactNode | undefined;} & React.RefAttributes<GlobeController>>
Root> );};
LEGS joins each stop in TRIP to the next, as the lines of features. A drag does not stop a tour, so the
onUpdate of useDrag calls setRunning(false) when a drag starts, and the useEffect starts the tour again.
The story at the top of this page flies the same trip.