MapViewport renders one MapTiler SDK map through React. Start with the basemap
below; add Visualization's DataOverlay as a child only when you need deck.gl or
raster layers. The package owns map behavior; Visualization owns overlays.
The full MapViewport, MapViewportProps and
MapViewportRef API is available alongside this guide.
This guide describes the current review candidate, not the previously published package. Install its reviewed tarball and the matching peers:
npm install ./un-fao-map-0.1.0-review.1.tgz \
@maptiler/sdk@4.1.0 maplibre-gl@5.24.0 react@19 react-dom@19 react-map-gl@8.1.3
The package is browser/client ESM and imports SDK CSS automatically. SDK 4.1.0 and its MapLibre 5.24.0 engine are aligned peers, not two renderer paths. Other bundlers and server rendering remain unverified. See the packaged README for verified tooling.
Give the parent non-zero dimensions. No account, key, style URL, ref or callback is needed for the internal OpenFreeMap Liberty default:
import { MapViewport } from '@un-fao/map';
export function BasicMap() {
return <div style={{ height: 480 }}>
<MapViewport initialViewState={{ longitude: 12.5, latitude: 41.9, zoom: 6 }} />
</div>;
}
| Module | Import | Purpose | Why or when |
|---|---|---|---|
@un-fao/map |
MapViewport |
Runtime-required | Renders the basemap and includes its stylesheet. |
Add types and a ref only when your application needs them:
import { createRef } from 'react';
import { MapViewport, type MapViewportProps, type MapViewportRef } from '@un-fao/map';
const mapRef = createRef<MapViewportRef>();
const props = { projection: 'globe', initialViewState: { zoom: 1 } } satisfies MapViewportProps;
export function TypedMap() {
return <div style={{ height: 480 }}><MapViewport {...props} ref={mapRef} /></div>;
}
| Module | Import | Purpose | Why or when |
|---|---|---|---|
react |
createRef |
Conditional: imperative access | Creates the optional map ref. |
@un-fao/map |
MapViewport |
Runtime-required | Renders this example's map. |
@un-fao/map |
MapViewportProps |
Optional type-only | Checks the configuration object. |
@un-fao/map |
MapViewportRef |
Conditional: imperative access | Types the optional map ref. |
createMapTilerBasemaps(key) returns independent entries named streets,
outdoor, satellite, hybrid, and dataviz. Each BasemapEntry has label,
style, and an optional thumbnailUrl. The five presets include original,
schematic SVG illustrations embedded in the package. They represent the style
category, not an exact map preview, and displaying them makes no MapTiler
thumbnail request. Style URLs use the installed SDK catalog's default variant
and encode the key. Blank keys throw. The helper makes no requests and changes
no SDK globals.
Use object spread to add or replace entries. Calling the helper again with a rotated key updates the style URLs while retaining the same illustrations; selecting a new style updates the existing map. Custom entries may provide their own image URL. A missing or failed image shows a neutral fallback regardless of MapTiler key or plan; the package does not generate custom thumbnails. A remote thumbnail URL makes a request to that host under its own terms. There is no key prop or automatic selection based on the presence of a key.
BasemapControl is a child of MapViewport, positioned at the top right. Its
basemaps, value and onChange(id) props are controlled by your application.
The 44 px trigger shows the current thumbnail inside a compact 30 px visual.
It opens one horizontally scrollable strip to the left. Added or overridden
styles appear first; unchanged entries returned by createMapTilerBasemaps
follow after a labeled divider when both groups exist. Mixed lists open at the
custom choices even when a preset is selected. Click or tap a card, or
focus it and press Enter or Space, to choose; arrow keys move focus, and Escape
closes the strip. Selection closes it and returns focus to the trigger. The
control passes stable IDs, never keyed URLs. It does not call setStyle or hold
selection state. You can omit it and supply your own UI. The unconfigured
OpenFreeMap-only path has one choice, so omit the selector there; the demo does
this. Removing it leaves the map unchanged.
When a controlled URL style changes on a loaded map, MapViewport may briefly
hold a local image of its last rendered canvas frame over the map while the
replacement loads. Capture is skipped above 2,000,000 device pixels or when
the browser cannot capture promptly; the style still changes normally. The
image fades when the new style is ready and is removed if the selected style
fails or becomes invalid, the camera moves, the projection changes, or the map
unmounts. The map instance, controls and overlays stay mounted. Capture does
not call MapTiler's Static Maps API or spend static-map requests. The image
does not include separate DOM controls or overlays; callers own their live
overlay and error presentation.
import { useMemo, useState } from 'react';
import { BasemapControl, createMapTilerBasemaps, MapViewport, type BasemapEntry, type BasemapControlProps } from '@un-fao/map';
export function PresetMap({ deploymentKey }: { deploymentKey: string }) {
const basemaps = useMemo(() => ({
...createMapTilerBasemaps(deploymentKey),
outdoor: { label: 'Our outdoor style', style: '/styles/outdoor.json' },
community: { label: 'OpenFreeMap', style: 'https://tiles.openfreemap.org/styles/liberty', thumbnailUrl: '/images/community-map.webp' } satisfies BasemapEntry,
}), [deploymentKey]);
const [value, setValue] = useState('streets');
const selected = Object.entries(basemaps).find(([id]) => id === value)?.[1];
if (!selected) return <p role="alert">Select an available basemap.</p>;
const control = { basemaps, value, onChange: setValue } satisfies BasemapControlProps;
return <div style={{ height: 480 }}>
<MapViewport mapStyle={selected.style}>
<BasemapControl {...control} />
</MapViewport>
</div>;
}
| Module | Import | Purpose | Why or when |
|---|---|---|---|
react |
useMemo |
Runtime-required | Rebuilds entries when the deployment key changes. |
react |
useState |
Runtime-required | Owns selected ID in this example. |
@un-fao/map |
BasemapControl |
Conditional: basemap selection | Adds the controlled selector. |
@un-fao/map |
BasemapEntry |
Optional type-only | Checks the custom entry. |
@un-fao/map |
BasemapControlProps |
Optional type-only | Checks the controlled selector configuration. |
@un-fao/map |
createMapTilerBasemaps |
Conditional: MapTiler presets | Constructs MapTiler style URLs. |
@un-fao/map |
MapViewport |
Runtime-required | Renders the selected style. |
| Prop | Type | Required? | Default | Ownership and effect |
|---|---|---|---|---|
basemaps |
Readonly<Record<string, BasemapEntry>> |
Required | No package default | Map-owned list of labeled styles. |
value |
string |
Required | No package default | Map-owned selected stable ID. |
onChange |
(id: string) => void |
Required | No package default | Map-owned callback for an explicit selection. |
An empty list shows a disabled trigger and a visible configuration message. A
missing selected ID shows the message while available choices stay selectable.
The control never
chooses the first entry or emits a change during render. Guard lookups as above;
otherwise an accidental undefined style would select the omission default.
MapControls is an optional child of MapViewport. It mounts one top-right
control with one-action zoom buttons and a two-action 2D/Tilt/Globe picker.
Pass basemap with the same controlled props as BasemapControl to add the
thumbnail selector; omit it when OpenFreeMap is the only style. The package
emits zoom, view and selected-basemap intents. Your application owns camera,
projection and selected style through MapViewport props. The control never
calls setStyle, setProjection or camera methods.
import { useRef, useState } from 'react';
import { MapControls, MapViewport, type MapControlsProps, type MapViewportRef } from '@un-fao/map';
export function CompactMap() {
const [camera, setCamera] = useState({ longitude: 12.5, latitude: 41.9, zoom: 6 });
const [view, setView] = useState<MapControlsProps['view']>('2d');
const mapRef = useRef<MapViewportRef>(null);
const zoom = (step: -1 | 1) => {
const map = mapRef.current?.getMap();
if (!map) return;
const target = Math.min(map.getMaxZoom(), Math.max(map.getMinZoom(), map.getZoom() + step));
map.zoomTo(target, { duration: window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 0 : 260 });
};
const selectView = (next: MapControlsProps['view']) => {
const map = mapRef.current?.getMap();
if (map?.isMoving()) {
map.stop();
const center = map.getCenter();
setCamera({ longitude: center.lng, latitude: center.lat, zoom: map.getZoom() });
}
setView(next);
};
return <div style={{ height: 330 }}>
<MapViewport {...camera} ref={mapRef}
onMove={event => setCamera({
longitude: event.viewState.longitude,
latitude: event.viewState.latitude,
zoom: event.viewState.zoom,
})}
projection={view === 'globe' ? 'globe' : 'mercator'}
pitch={view === 'tilt' ? 60 : 0}
bearing={view === 'tilt' ? -20 : 0}>
<MapControls view={view} onViewChange={selectView}
onZoomIn={() => zoom(1)} onZoomOut={() => zoom(-1)} />
</MapViewport>
</div>;
}
| Module | Import | Purpose | Why or when |
|---|---|---|---|
react |
useRef |
Runtime-required | Holds the map ref used for animated zoom. |
react |
useState |
Runtime-required | Owns controlled camera and View state. |
@un-fao/map |
MapViewport |
Runtime-required | Renders the map with controlled camera and projection. |
@un-fao/map |
MapControls |
Runtime-required | Emits compact navigation and View intents. |
@un-fao/map |
MapControlsProps |
Optional type-only | Types the controlled View state. |
@un-fao/map |
MapViewportRef |
Optional type-only | Types the map ref used for animated zoom. |
For a configured map, clamp zoom intents to the map's current minimum and
maximum zoom and pass zoomInDisabled and zoomOutDisabled at the limits.
Keep onMove and any application fitBounds action synchronized with the
same camera state. This short example stops an active map animation before
changing View. For repeated zoom clicks before completion, track and finish
the pending target as the demo does.
basemap accepts BasemapControlProps; its missing or
invalid selected ID keeps the same visible status and valid choices as the
standalone selector. Hovering a trigger opens its strip for a mouse or pen;
click, touch and keyboard activation also work. The two choice strips open left,
one at a time, and scroll horizontally by touch, wheel, keyboard or the visible
edge buttons. Selection, Escape and an outside
pointer close a strip; keyboard focus returns to its trigger. At small map
heights, zoom buttons share a row when a vertical column would cover visible
attribution. View modes change no terrain or buildings. Native map gestures
outside the controls are unchanged.
| Prop | Type | Required? | Default | Ownership and effect |
|---|---|---|---|---|
basemap |
BasemapControlProps |
Optional | No basemap trigger | Map-owned picker input; app owns selection and style. |
view |
"globe" | "2d" | "tilt" |
Required | No package default | App-owned active View shown on the trigger. |
onViewChange |
(view: "2d" | "tilt" | "globe") => void |
Required | No package default | Map-owned intent callback; app updates projection and camera props. |
onZoomIn |
() => void |
Required | No package default | Map-owned zoom-in intent. |
onZoomOut |
() => void |
Required | No package default | Map-owned zoom-out intent. |
zoomInDisabled |
boolean |
Optional | false |
Map-owned disabled state for zoom-in at the app's current maximum. |
zoomOutDisabled |
boolean |
Optional | false |
Map-owned disabled state for zoom-out at the app's current minimum. |
MapViewportProps preserves compatible React map props, refs, children and
events. mapLib is package-owned. Public transformRequest and
showBasemap3dBuildings are removed, including from untyped prop spreads.
| Prop | Type | Required? | Default | Ownership and effect |
|---|---|---|---|---|
mapStyle |
NonNullable<string | StyleSpecification | ImmutableLike<StyleSpecification> | undefined> |
Optional | Internal OpenFreeMap Liberty | Map-owned; explicit URL/object overrides the default. |
projection |
ProjectionSpecification | "mercator" | "globe" |
Optional | No package default | Inherited input applied after commit when the style is ready. |
onLoad |
(e: MapLibreEvent) => void |
Optional | No package default | Inherited callback; forwards the real map load event. |
onStyleData |
(e: MapStyleDataEvent) => void |
Optional | No package default | Inherited callback; forwards upstream style data events. |
All listed props are optional. No package default means the upstream behavior
applies. See the generated reference for MapViewportProps and the official
React map API
for other inherited props. Supplying undefined, including after an explicit
style, selects Liberty. Explicit null, blank URLs and malformed styles are errors.
Invalid initial configuration needs an application error boundary; reset it after
correcting the configuration. Invalid updates report onError and retain the
previous good style. Root URLs must resolve to HTTP(S); inline version 8 and
compatible immutable style objects are supported. TileJSON alone is not a style.
Mercator supports ordinary 2D and pitched camera views; projection="globe"
selects globe. Projection changes wait for style readiness, including on retry,
and retain the latest requested value while loading. Camera props remain
controlled through the React wrapper. Use an initial camera for uncontrolled
interaction, or update controlled camera state as the user moves the map; a
fixed controlled view does not follow drag/zoom. The package adds no buildings. Layers
provided by the selected style are left intact. New terrain, scientific raster
draping and interleaved overlays are deferred; overlays retain separate canvases.
MapViewportRef is the compatible public React map ref. Use it only when you
need imperative access; unmounting releases the map. Failed network loads report
onError and keep the component mounted. Show an error and explicit retry using
ref.current?.getMap().setStyle(selectedStyle) with the same selected URL or
plain style object. For immutable styles pass selectedStyle.toJS(). A retry is
not success: wait for actual readiness and handle another error. There is no
automatic provider fallback or retry.
Do not retain the ref after unmount. Applications own accessible surrounding controls, labels, keyboard instructions and non-map alternatives; the canvas alone is not a complete accessible experience. If the map is blank, check its container dimensions and style/resource requests. A successful map load callback does not prove every remote resource is available.
Custom styles supply their own authentication, including nested sources, sprites, glyphs and tiles. Query parameters on the root URL do not generically authenticate nested resources. Already-authenticated and legitimately keyless styles are supported without dummy credentials. Callers own domain restrictions, rotation and usage; browser visibility of public map keys is expected.
SDK sessions and caching keep native processing. Shared-instance telemetry is disabled before construction and remains disabled after unmount, affecting all maps using that SDK instance. Hosts must leave it disabled. No host key is set or cleared by the package. The SDK can warn about a missing global key even when an authenticated style works; check the actual resource outcome.
SDK limitation: do not configure a shared global SDK key for this integration. SDK 4.1.0 may inherit that key on unkeyed Cloud requests and append it to external TileJSON metadata requests, including dynamically added sources. This upstream behavior is accepted; the package does not promise credential isolation. Provider domain restrictions can reduce misuse but do not prevent forwarding. Supply keys only for resources/providers you intend to use and follow your provider's restriction, rotation and usage guidance. The package sets no global key.
defaultMapStyle, dedicated CARTO support, CARTO building extrusion,
showBasemap3dBuildings, and public transformRequest are retired. Use omission
for Liberty, the preset helper for MapTiler, or a complete custom style. No public
default-style constant replaces the removed export. Provider-owned layers and
ordinary style objects remain supported. Use the selected artifact's declarations
and guide, not the historical published version's API.
Consumers relying on custom request headers, URL rewriting or proxies must stay on the previous compatible package version or adapt their style and nested resource URLs to work directly. Supplying a root style URL alone does not preserve those request-hook configurations. Native map refs remain available for ordinary map access, but are not a supported workaround for the retired prop.