ThreeView Functions
This page describes all functions (methods) available on a ThreeView instance.
Methods
Section titled “Methods”addLayer()
Section titled “addLayer()”Adds a new resource layer to navara_three. This method is used for resource layers only (vector, raster, terrain, 3d-tiles). Each resource layer references a source via its source property. For mesh, light, and effect descriptors, use addMesh(), addLight(), and addEffect() respectively.
Syntax:
addLayer(l: LayerDescription): LayerParameters:
For layer configuration options, see Layer Types and each layer type page.
Returns:
Layer;Returns a Layer instance for the added resource layer.
Example:
const source = view.addSource({ type: "raster-tile", url: "https://cyberjapandata.gsi.go.jp/xyz/seamlessphoto/{z}/{x}/{y}.jpg", maxZoom: 23,});
const layer = view.addLayer({ type: "raster", source, raster: { color: new Color().setStyle("#cccccc"), },});addSource()
Section titled “addSource()”Registers a data source and returns a Source handle. A source describes where data comes from and how it is fetched/decoded. Reference it from a resource layer via the layer’s source property (the handle or its id).
Syntax:
addSource(s: SourceDescription): SourceParameters:
For the available source types and their fields, see About Source.
Returns:
Source;A Source handle exposing id, type, update(s), and delete().
Example:
const imagery = view.addSource({ type: "raster-tile", url: "https://example.com/{z}/{x}/{y}.png", maxZoom: 19,});
view.addLayer({ type: "raster", source: imagery });
// Laterimagery.update({ type: "raster-tile", url: "https://example.com/new/{z}/{x}/{y}.png" });imagery.delete();addMesh()
Section titled “addMesh()”Adds a new mesh descriptor to navara_three. The mesh descriptor class must be registered with registerMesh() before calling this method.
Syntax:
addMesh<L = unknown>(l: MeshDescription): MeshHandle<L>Returns:
MeshHandle<L>;Returns a MeshHandle<L> for controlling the mesh descriptor.
Example:
// SkyMeshDesc must be registeredconst skyHandle = view.addMesh<SkyMeshDesc>({ sky: {} });addLight()
Section titled “addLight()”Adds a new light descriptor to navara_three. The light descriptor class must be registered with registerLight() before calling this method.
Syntax:
addLight<L = unknown>(l: LightDescription): LightHandle<L>Returns:
LightHandle<L>;Returns a LightHandle<L> for controlling the light descriptor.
Example:
// SunLightDesc must be registeredconst sunHandle = view.addLight<SunLightDesc>({ sun: { intensity: 1.0 } });addEffect()
Section titled “addEffect()”Adds a new effect descriptor to navara_three. The effect descriptor class must be registered with registerEffect() before calling this method.
Syntax:
addEffect<L = unknown>(l: EffectDescription): EffectHandle<L>Returns:
EffectHandle<L>;Returns a EffectHandle<L> for controlling the effect descriptor.
Example:
// FXAAEffectDesc must be registeredconst fxaaHandle = view.addEffect<FXAAEffectDesc>({ fxaa: {} });updateLayerById()
Section titled “updateLayerById()”Updates an existing resource layer’s configuration by its ID.
Only works for resource layers added via addLayer().
Syntax:
updateLayerById(id: string, l: LayerDescription): voidParameters:
id: The unique identifier of the layer to updatel: Specifies the properties to update
Example:
const id = layer.id; // Get the layer ID from the addLayer return value
// `source` is the raster-tile source referenced by the layer.view.updateLayerById(id, { type: "raster", source, raster: { color: new Color().setStyle("#ffffff"), },});updateMeshById()
Section titled “updateMeshById()”Updates an existing mesh descriptor’s configuration by its ID.
Accepts the same descriptor shape as addMesh().
Syntax:
updateMeshById(id: string, updates: OmitType<MeshConfig | D["mesh"]>): voidParameters:
id: The unique identifier of the mesh to updateupdates: Configuration object with properties to update (same shape asaddMesh())
Example:
const handle = view.addMesh<BoxMeshDesc>({ box: { width: 100 } });
view.updateMeshById(handle.id, { box: { width: 200 } });updateLightById()
Section titled “updateLightById()”Updates an existing light descriptor’s configuration by its ID.
Accepts the same descriptor shape as addLight().
Syntax:
updateLightById(id: string, updates: OmitType<LightConfig | D["light"]>): voidParameters:
id: The unique identifier of the light to updateupdates: Configuration object with properties to update (same shape asaddLight())
Example:
const handle = view.addLight<SunLightDesc>({ sun: { intensity: 1.0 } });
view.updateLightById(handle.id, { sun: { intensity: 0.5 } });updateEffectById()
Section titled “updateEffectById()”Updates an existing effect descriptor’s configuration by its ID.
Accepts the same descriptor shape as addEffect().
Syntax:
updateEffectById(id: string, updates: OmitType<BuiltInEffectDescription | EffectConfig | D["effect"]>): voidParameters:
id: The unique identifier of the effect to updateupdates: Configuration object with properties to update (same shape asaddEffect())
Example:
const handle = view.addEffect<SSAOEffectDesc>({ ssao: { radius: 0.5 } });
view.updateEffectById(handle.id, { ssao: { radius: 1.0 } });deleteLayerById()
Section titled “deleteLayerById()”Deletes a resource layer from the scene by its ID.
Syntax:
deleteLayerById(id: string): booleanParameters:
id: The unique identifier of the layer to delete
Returns: true if the layer was found and deleted, false otherwise.
Example:
const id = layer.id;
view.deleteLayerById(id);deleteMeshById()
Section titled “deleteMeshById()”Deletes a mesh descriptor from the scene by its ID.
Syntax:
deleteMeshById(id: string): booleanParameters:
id: The unique identifier of the mesh to delete
Returns: true if the mesh was found and deleted, false otherwise.
Example:
view.deleteMeshById(handle.id);deleteLightById()
Section titled “deleteLightById()”Deletes a light descriptor from the scene by its ID.
Syntax:
deleteLightById(id: string): booleanParameters:
id: The unique identifier of the light to delete
Returns: true if the light was found and deleted, false otherwise.
Example:
view.deleteLightById(handle.id);deleteEffectById()
Section titled “deleteEffectById()”Deletes an effect descriptor from the scene by its ID.
Syntax:
deleteEffectById(id: string): booleanParameters:
id: The unique identifier of the effect to delete
Returns: true if the effect was found and deleted, false otherwise.
Example:
view.deleteEffectById(handle.id);init()
Section titled “init()”Initializes the 3D engine and WASM modules, and starts the main rendering loop. You must call this method before using the view.
Syntax:
async init(): Promise<void>Returns:
A Promise<void> that resolves when initialization is complete.
Example:
const view = new ThreeView();await view.init();
// Add layers after init()const osm = view.addSource({ type: "raster-tile", url: "https://tile.openstreetmap.org/{z}/{x}/{y}.png", maxZoom: 19,});
view.addLayer({ type: "raster", source: osm });dispose()
Section titled “dispose()”Releases all resources and stops the rendering loop. Call this method when the view is no longer needed. The worker pool shared with other views on the page stays alive until the last view is disposed (see Multiple Views).
It is safe to call while init() is pending; that init() then resolves without starting the view. A disposed view cannot be initialized again.
Syntax:
dispose(): voidExample:
// Cleanup on component unmountview.dispose();resize()
Section titled “resize()”Changes the renderer size and updates the camera aspect ratio. Automatically called when the container changes size unless disableAutoResize is true.
Syntax:
resize(width?: number, height?: number, pixelRatio?: number): voidParameters:
width: New width (pixels). Uses canvas size when omittedheight: New height (pixels). Uses canvas size when omittedpixelRatio: Device pixel ratio
Example:
// Resize with explicit dimensionsview.resize(1920, 1080, 2);
// Resize using current canvas size (only updating pixel ratio)view.resize(undefined, undefined, window.devicePixelRatio);getCamera()
Section titled “getCamera()”Returns the camera as of the last frame, as a plain object: position, orientation and field of view. The object is JSON-safe, and setCamera() takes it back as is, so it can save and restore a view.
Syntax:
getCamera(): CameraState | undefinedReturns:
type CameraState = { lng: number; lat: number; height: number; heading: number; pitch: number; roll: number; fov: number;};| Field | Type | Description |
|---|---|---|
lng | number | Longitude (degrees) |
lat | number | Latitude (degrees) |
height | number | Height above the ellipsoid (meters) |
heading | number | Heading angle (degrees, 0 = North, clockwise) |
pitch | number | Pitch angle (degrees, negative = looking down) |
roll | number | Roll angle (degrees) |
fov | number | Vertical field of view (degrees) |
Returns undefined until the engine camera exists: during a plugin’s init(), and until the first frame after view.init() resolves.
Example:
// Save the view, for example to localStorage.const camera = view.getCamera();if (camera) localStorage.setItem("camera", JSON.stringify(camera));
// Restore it later.const saved = localStorage.getItem("camera");if (saved) view.setCamera(JSON.parse(saved));setCamera()
Section titled “setCamera()”Sets the camera position and orientation without animation. The engine applies it on the next frame, so getCamera() returns the old camera until then.
Syntax:
setCamera(camPos: CameraPosition & { fov?: number }): voidParameters:
camPos: Camera position and orientation, and optionally the field of view. The result ofgetCamera()can be passed as is.
type CameraPosition = { lng?: number; lat?: number; height?: number; pitch?: number; heading?: number; roll?: number; distance?: number;};| Field | Type | Description |
|---|---|---|
lng | number | Longitude (degrees) |
lat | number | Latitude (degrees) |
height | number | Height above the ellipsoid (meters). When distance is also set, this is used as the target point elevation: the camera is placed distance meters from that elevated target. |
pitch | number | Pitch angle (degrees) |
heading | number | Heading angle (degrees) |
roll | number | Roll angle (degrees) |
distance | number | Distance from the target point along the camera forward direction (meters). When specified, the camera is placed so that its forward ray reaches the lng/lat/height target from this distance. If omitted, height is used as the camera’s own altitude above the surface normal. |
fov | number | Vertical field of view (degrees, 1–179), the same as setting camera.fov. Values outside this range (and NaN) are ignored. If omitted, the field of view does not change. A call with only fov changes only the field of view: it does not stop a flight. |
Example:
// Altitude-based: place the camera 1000 m above Tokyo along the surface normalview.setCamera({ lng: 139.7671, lat: 35.6812, height: 1000, pitch: -45, heading: 0, roll: 0,});
// Distance-based: frame a mountain summit (height = 3776 m) from 5000 m awayview.setCamera({ lng: 138.7274, lat: 35.3606, height: 3776, distance: 5000, pitch: -20, heading: 0,});moveCamera()
Section titled “moveCamera()”Moves the camera in the specified direction by the specified amount.
Syntax:
moveCamera(move: CameraDirection, amount: number): voidParameters:
move: Camera movement directionamount: Amount to move (meters)
CameraDirection is an enum with the following values:
enum CameraDirection { Forward, Backward, Left, Right, Up, Down,}Example:
import ThreeView, { CameraDirection } from "@navaramap/three";
view.moveCamera(CameraDirection.Forward, 100);view.moveCamera(CameraDirection.Up, 50);moveCameraWithDirection()
Section titled “moveCameraWithDirection()”Moves the camera with a custom direction vector.
Syntax:
moveCameraWithDirection(dir: number[], amount: number): voidParameters:
dir: [x, y, z] direction vectoramount: Amount to move (meters)
Example:
view.moveCameraWithDirection([1, 0, 0], 100);flyTo()
Section titled “flyTo()”Animates the camera to a target position. Moves smoothly along a flight arc: the longitude takes the short way across the antimeridian, and the height follows an arc that peaks at maxHeight.
The returned promise resolves to true when the flight completes, or false when it is interrupted by another camera operation, such as a newer flyTo() or a setCamera() call. Issuing a new flyTo() while a flight is in progress interrupts the current flight and starts the new one from the current camera pose.
Syntax:
flyTo( camPos: CameraPosition & Required<Pick<CameraPosition, "lng" | "lat">> & ({ height: number } | { distance: number }), options?: FlyToOptions): Promise<boolean>
type FlyToOptions = { duration?: number; maxHeight?: number; easing?: FlyToEasing;};
type FlyToEasing = | "linear" | "quadInOut" | "cubicInOut" | "cubicOut" | "quinticInOut";Parameters:
camPos: Target position.lngandlatare required, plus eitherheightordistance.lng: Longitude (degrees), requiredlat: Latitude (degrees), requiredheight: Height above the ellipsoid (meters). Whendistanceis also set, this is used as the target point elevation rather than the camera’s own altitude.pitch: Pitch angle (degrees)heading: Heading angle (degrees)roll: Roll angle (degrees)distance: Distance from the target point along the camera forward direction (meters). When specified, the camera is placed so that its forward ray reaches thelng/lat/heighttarget from this distance. If omitted,heightis used as the camera’s own altitude above the surface normal.
options: Flight options.duration: Animation duration (milliseconds). When omitted, the duration is derived from the flight distance (2–3 seconds). Pass0to jump instantly.maxHeight: Maximum height during the flight arc (meters)easing: Easing preset applied to the flight time. When omitted,"quinticInOut"is used, or"cubicOut"when descending from above 11,500 m.
Returns: Promise<boolean>: true when the flight completed, false when it was interrupted.
Example:
// Altitude-based: fly to Tokyo over 3 seconds (maximum height 5000 m)const completed = await view.flyTo( { lng: 139.7671, lat: 35.6812, height: 1000, pitch: -45, heading: 0, }, { duration: 3000, maxHeight: 5000 });if (!completed) { // Interrupted by another camera operation (a newer flyTo, setCamera, etc.).}
// Distance-based: approach Tokyo Tower (at ground level) from 2000 m away,// with an explicit easingview.flyTo( { lng: 139.7454, lat: 35.6586, height: 0, distance: 2000, pitch: -30, heading: 45, }, { duration: 4000, easing: "cubicInOut" });fitBounds()
Section titled “fitBounds()”Flies the camera so that a box or a set of positions fills the canvas, less the padding. The camera ends at the closest position, for the given heading and pitch, from which every position is inside the padded frame. The positions touch the padded frame on one axis and are centered on the other. The fit accounts for the canvas aspect ratio, the vertical field of view and the curvature of the Earth: a box is sampled along its edges, not only at its corners.
heading and pitch are those of the camera itself, measured in the local frame at its own position, and roll ends at 0. getCamera() reports the same values for a city-scale extent and within about 0.1° for a continent-wide one. Positions without height are at 0 m above the ellipsoid. The terrain under them is not sampled, so pass heights (for example from sampleTerrainMostDetailed()) to frame hilly ground. Every position stays at least 300 m in front of the camera along its forward direction, so a single position is seen from 300 m. fitBounds() can be called right after init(), before the first frame, for example to frame the data a page opens on. Calls take effect in order with the other camera methods, so a setCamera() or flyTo() made after fitBounds() overrides it. If the canvas is resized before the flight ends, the fit is solved again for the new size. A resize after that does not refit, so call fitBounds() again from a resize handler if needed. The cost grows with the number of positions: for a large feature, pass a box or a few representative positions instead of every vertex.
Syntax:
fitBounds( target: FitBoundsTarget, options?: FitBoundsOptions): Promise<boolean>
type FitBoundsTarget = | { west: number; south: number; east: number; north: number } | { lng: number; lat: number; height?: number }[];
type FitBoundsOptions = FlyToOptions & { padding?: | number | { top?: number; right?: number; bottom?: number; left?: number }; heading?: number; pitch?: number;};Parameters:
target: What to frame.- A box
{ west, south, east, north }in degrees.westgreater thaneastcrosses the antimeridian. - Or positions
{ lng, lat, height? }: degrees, and meters above the ellipsoid (default0).
- A box
options: Fit and flight options.padding: Space to keep free at the canvas edges (CSS pixels), for all four sides or per side. Default0.heading: Heading (degrees, clockwise from north). Defaults to the current camera’s, or0before the first frame.pitch: Pitch (degrees, from-90, straight down, up to but not including0). Defaults to the current camera’s, or-90before the first frame.duration,maxHeight,easing: As inflyTo().duration: 0jumps without a flight.
Returns: Promise<boolean>: as for flyTo(), true when the flight completed and false when it was interrupted. It is also false, without moving the camera, when there are no positions, the padding leaves no room in the canvas, the pitch is outside [-90, 0), or no camera at that heading and pitch frames the positions while staying above the ground and seeing all of them over the Earth’s horizon. The last case happens with a large extent at an oblique pitch, for example a box spanning most of a continent at pitch: -45.
Example:
// A start point and nearby shelters, seen at 45 degrees, clear of a// 320 px side panel on the leftconst start = { lng: 139.7671, lat: 35.6812 };const shelters = [ { lng: 139.756, lat: 35.6735 }, { lng: 139.758, lat: 35.6852 }, { lng: 139.7633, lat: 35.66 },];await view.fitBounds([start, ...shelters], { padding: { top: 40, right: 40, bottom: 40, left: 360 }, heading: 0, pitch: -45,});
// A box, straight down, without a flightview.fitBounds( { west: 138.4, south: 34.9, east: 140.9, north: 36.9 }, { padding: 40, pitch: -90, duration: 0 });lookAt()
Section titled “lookAt()”Points the camera at a target position and places it at an offset position. The offset is specified in the East-North-Up (ENU) coordinate system.
Syntax:
lookAt(target: LatLngHeight, offset: Vector3): voidParameters:
target: Target geodetic positionlng: Longitude (degrees)lat: Latitude (degrees)height: Height (meters)
offset: Offset from the target (ENU coordinate system, meters)x: East directiony: North directionz: Up direction
Example:
import { Vector3 } from "three";
// Look down at Tokyo Tower from 1000m aboveview.lookAt( { lng: 139.7454, lat: 35.6586, height: 0 }, new Vector3(0, 0, 1000) // 1000m directly above);
// View from a diagonal behindview.lookAt( { lng: 139.7454, lat: 35.6586, height: 0 }, new Vector3(500, -500, 500) // 500m east, 500m south, 500m up);cameraFollow()
Section titled “cameraFollow()”Enables or disables camera follow mode. When enabled, the camera moves centered on the specified target position.
Syntax:
cameraFollow(enabled: boolean, target?: LatLngHeight, offset?: Vector3): voidParameters:
enabled: Whether to enable follow modetarget: Target position to center onlng: Longitude (degrees)lat: Latitude (degrees)height: Height (meters)
offset: Offset from the target (ENU coordinate system, meters)
Example:
import { Vector3 } from "three";
view.cameraFollow( true, { lng: 139.7671, lat: 35.6812, height: 100 }, new Vector3(0, -200, 100) // 200m south, 100m up);
// Disable follow modeview.cameraFollow(false);cameraFreeLook()
Section titled “cameraFreeLook()”Enables or disables position-locked free-look. The camera stays planted at the target position while mouse drag rotates orientation in place. Useful for first-person-view “look around” controls where the eye must not move.
Syntax:
cameraFreeLook(enabled: boolean, target?: LatLngHeight): voidParameters:
enabled: Whether to enable free-look modetarget: Target position the camera is locked tolng: Longitude (degrees)lat: Latitude (degrees)height: Height (meters)
When the target moves between calls (e.g. the player walks), the camera translates with it. Orientation is preserved. Mouse wheel zoom is disabled in this mode (the camera is at zero distance from the pivot).
Example:
// Lock the camera at the player's eye position; drag to look aroundview.cameraFreeLook(true, { lng: 139.7671, lat: 35.6812, height: 105 });
// Disable free-look modeview.cameraFreeLook(false);sampleTerrainHeight()
Section titled “sampleTerrainHeight()”Synchronously gets the terrain height at a specified geodetic position. Returns undefined if terrain data has not yet been loaded. When exaggeration is set, the returned heights are exaggerated to match the rendered surface.
This reads only tiles already resident for rendering, so while the camera is far away it returns the height of a coarse LOD tile which can be tens of meters off the true ground height. When you need an accurate height regardless of the camera (for example to place an object on the ground), use sampleTerrainMostDetailed() instead.
Syntax:
sampleTerrainHeight(pos: LatLng): number | undefinedParameters:
pos: Geodetic positionlat: Latitude (degrees)lng: Longitude (degrees)
Returns:
Terrain height (meters), or undefined if terrain data is not available
Example:
// Specify latitude and longitude in degreesconst lat = 35.6812;const lng = 139.7671;
const height = view.sampleTerrainHeight({ lat, lng });
if (height !== undefined) { console.log(`Terrain height: ${height}m`);} else { console.log("Terrain data has not been loaded yet");}sampleTerrainMostDetailed()
Section titled “sampleTerrainMostDetailed()”Asynchronously samples terrain heights at the most detailed zoom level the terrain source provides, fetching the needed tiles over the network. Unlike sampleTerrainHeight(), which reads only tiles already resident for rendering, and therefore returns coarse heights (or undefined) while the camera is far away, this resolves accurate ground heights regardless of what the camera has streamed in. Use it to place objects on the ground before flying there. When the terrain layer rendering source sets exaggeration, the returned heights are exaggerated to match the rendered surface.
Positions are grouped by tile and each unique tile is fetched once. Sampling starts at the source’s maxZoom and falls back to parent tiles on 404 until data is found, so sources whose real coverage is shallower than the configured maxZoom still resolve. A 401/403 response rejects the whole call (a token problem should not silently degrade into coarse heights), while server errors are retried and then yield height: undefined for the affected positions.
Syntax:
sampleTerrainMostDetailed( source: SourceRef, positions: LatLng[], options?: SampleTerrainOptions,): Promise<SampledTerrainPosition[]>Parameters:
source: A registeredquantized-mesh/raster-demsource: either theSourcehandle returned byaddSource, or its idpositions: Geodetic positions to samplelat: Latitude (degrees)lng: Longitude (degrees)
options.level: Sample at this fixed zoom level instead of probing down from the source’smaxZoom. With a fixed level there is no fallback to parent tiles.options.signal:AbortSignalto cancel in-flight tile fetches.
Returns:
A promise resolving to one result per input position, in the same order. Each result echoes lat/lng and carries height (meters, or undefined when no tile could be fetched or decoded) and level (the zoom level actually sampled).
Example:
const terrain = view.addSource({ type: "quantized-mesh", url: "https://example.com/{z}/{x}/{y}.terrain", maxZoom: 15,});view.addLayer({ type: "terrain", source: terrain });
const lat = 35.6812;const lng = 139.7671;
const [ground] = await view.sampleTerrainMostDetailed(terrain, [{ lat, lng }]);if (ground.height !== undefined) { // Place a model exactly on the terrain surface, even from far away const surface = geodeticToVector3({ lat, lng, height: ground.height }); view.addMesh({ gltfModel: { url: "https://example.com/model.glb" }, matrixWorld: northUpEastToFixedFrame(surface), });}observeTerrainHeightAt()
Section titled “observeTerrainHeightAt()”Monitors terrain height changes at a specific position. The callback is invoked once the height is first sampled, which happens right after registration when the terrain there is already loaded, and then whenever a terrain tile containing the position loads or the terrain exaggeration changes, and the height changes with it. When exaggeration is set, the returned heights are exaggerated to match the rendered surface.
Syntax:
observeTerrainHeightAt(pos: LatLng, cb: (height: number) => void): () => voidParameters:
pos: Position to monitorlat: Latitude (degrees)lng: Longitude (degrees)
cb: Callback invoked when the height is updated
Returns:
A cleanup function to stop monitoring
Example:
// Specify latitude and longitude in degreesconst lat = 35.6812;const lng = 139.7671;
const cleanup = view.observeTerrainHeightAt({ lat, lng }, (height) => { console.log(`Terrain height updated: ${height}m`);});
// Stop monitoring latercleanup();sampleTerrainHeightRange()
Section titled “sampleTerrainHeightRange()”Synchronously gets the minimum and maximum height of the ground over a geographic extent. Like sampleTerrainHeight(), it reads only the terrain tiles already loaded for rendering, and it reports 0 for an area no terrain tile has loaded yet. Use it to size something that must enclose the ground, for example a volume reaching from below to above the terrain. When exaggeration is set, the range is exaggerated to match the rendered surface, and so is the 0 of an area not loaded yet.
Syntax:
sampleTerrainHeightRange( extent: GeographicExtent,): { min: number; max: number } | undefinedParameters:
extent: Geographic boundswest: Western longitude (degrees)south: Southern latitude (degrees)east: Eastern longitude (degrees)north: Northern latitude (degrees)
Returns:
The minimum and maximum height (meters, relative to the ellipsoid), or undefined before the engine has set up its terrain
Example:
const range = view.sampleTerrainHeightRange({ west: 138.7, south: 35.3, east: 138.8, north: 35.4,});
if (range) { console.log(`Ground spans ${range.min}m to ${range.max}m`);}observeTerrainHeightRange()
Section titled “observeTerrainHeightRange()”Monitors the result of sampleTerrainHeightRange() over an extent. The callback is invoked once the range is first computed, and then whenever a terrain tile overlapping the extent loads or the terrain exaggeration changes, and the range changes with it.
Syntax:
observeTerrainHeightRange( extent: GeographicExtent, cb: (range: { min: number; max: number }) => void,): () => voidParameters:
extent: Geographic bounds in degrees, as insampleTerrainHeightRange().westmust not be greater thaneast, so an extent crossing the antimeridian is not supported.cb: Callback receiving the minimum and maximum height (meters, relative to the ellipsoid)
Returns:
A cleanup function to stop monitoring
Example:
const cleanup = view.observeTerrainHeightRange( { west: 138.7, south: 35.3, east: 138.8, north: 35.4 }, ({ min, max }) => { console.log(`Ground spans ${min}m to ${max}m`); },);
// Stop monitoring latercleanup();rotateAroundAxis()
Section titled “rotateAroundAxis()”Rotates the camera around a specified axis. Specifying a zero vector uses the default axis.
Syntax:
rotateAroundAxis(axis: Vector3, angle: number): voidParameters:
axis: Rotation axisangle: Rotation angle (radians)
Example:
import { Vector3 } from "three";
// Rotate 45 degrees around the Y axisview.rotateAroundAxis(new Vector3(0, 1, 0), Math.PI / 4);rotateAround()
Section titled “rotateAround()”Rotates the camera around the current look-at point or the center of the view.
Syntax:
rotateAround(angle: number): voidParameters:
angle: Rotation angle (radians)
Example:
// Rotate 45 degreesview.rotateAround(Math.PI / 4);
// Auto-rotation animationconst animate = () => { view.rotateAround(0.005); requestAnimationFrame(animate);};animate();forceUpdate()
Section titled “forceUpdate()”Forces the scene to re-render on the next frame. Used to manually trigger an update when animation: false.
Syntax:
forceUpdate(): voidExample:
view.forceUpdate();pickTerrainPosition()
Section titled “pickTerrainPosition()”Picks the terrain position under a pointer. The coordinates are client coordinates in CSS pixels, such as clientX and clientY of a mouse event: relative to the viewport, not to the canvas. When the view renders to an OffscreenCanvas (for example in a worker), which has no position on the page, the coordinates are relative to the canvas instead.
Syntax:
pickTerrainPosition(x: number, y: number): Vector3 | nullParameters:
x: Client X coordinate (CSS pixels,MouseEvent.clientX), relative to the viewporty: Client Y coordinate (CSS pixels,MouseEvent.clientY), relative to the viewport
Returns:
World position (ECEF coordinates), or null if no terrain is hit
Example:
// Get terrain coordinates at the click positionview.on("click", (event) => { const position = view.pickTerrainPosition(event.clientX, event.clientY); if (position) { console.log(`ECEF coordinates: ${position.x}, ${position.y}, ${position.z}`); } else { console.log("No terrain hit"); }});pickDepthPosition()
Section titled “pickDepthPosition()”Picks the world position under a pointer using the full scene depth buffer. The coordinates are client coordinates, as for pickTerrainPosition(). Unlike pickTerrainPosition(), this method reads from the combined depth texture that includes all rendered geometry (terrain, meshes, etc.), so it returns a hit even when non-terrain objects are in front of the terrain.
Syntax:
pickDepthPosition(x: number, y: number): Vector3 | nullParameters:
x: Client X coordinate (CSS pixels,MouseEvent.clientX), relative to the viewporty: Client Y coordinate (CSS pixels,MouseEvent.clientY), relative to the viewport
Returns:
World position (ECEF coordinates), or null if nothing is hit
Example:
view.on("click", (event) => { const position = view.pickDepthPosition(event.clientX, event.clientY); if (position) { console.log(`ECEF coordinates: ${position.x}, ${position.y}, ${position.z}`); } else { console.log("Nothing hit"); }});registerMesh()
Section titled “registerMesh()”Registers a custom mesh descriptor class.
Syntax:
registerMesh(name: string, meshClass: MeshDescConstructor): voidParameters:
name: Name of the mesh descriptor to registermeshClass: Constructor of the mesh descriptor
Example:
class CustomMeshDesc extends MeshDesc { onCreate() { // Custom implementation }}
view.registerMesh("customMesh", CustomMeshDesc);registerLight()
Section titled “registerLight()”Registers a custom light descriptor class.
Syntax:
registerLight(name: string, lightClass: LightDescConstructor): voidParameters:
name: Name of the light descriptor to registerlightClass: Constructor of the light descriptor
Example:
class CustomLightDesc extends LightDesc { onCreate() { // Custom implementation }}
view.registerLight("customLight", CustomLightDesc);registerEffect()
Section titled “registerEffect()”Registers a custom effect descriptor class.
Syntax:
registerEffect(name: string, effectClass: EffectDescConstructor): voidParameters:
name: Name of the effect descriptor to registereffectClass: Constructor of the effect descriptor
Example:
class CustomEffectDesc extends EffectDesc { onCreate() { // Custom implementation }}
view.registerEffect("customEffect", CustomEffectDesc);addPlugin()
Section titled “addPlugin()”Registers a plugin. Must be called before view.init().
Syntax:
addPlugin(plugin: Plugin): thisParameters:
plugin: APlugininstance
Example:
const view = new ThreeView({});view.addPlugin(pluginA).addPlugin(pluginB);await view.init();addFontFamily()
Section titled “addFontFamily()”Registers a font family composed of multiple faces. Each face covers a set of unicode ranges and points to a separate font file URL (ttf, otf, woff, or woff2). Once a family is registered, a text layer can reference it by its family name through material.font. Only the faces whose unicode ranges cover the characters in the label’s text are downloaded.
Face priority and fallback:
- Faces are evaluated in the order they appear in
faces. For each codepoint intext, the first face whoseunicodeRangescontain the codepoint is used, so if ranges overlap, the earlier entry wins. - Codepoints that are not covered by any face fall back to the first face (
faces[0]). This means the first face may also be downloaded for uncovered characters, even if its declaredunicodeRangesdo not include them.
To make this behavior predictable, put the face you want used as the fallback at index 0. Then order the remaining faces after it so that, when their ranges overlap, earlier entries have higher priority.
Returns the ThreeView instance so calls can be chained.
Syntax:
addFontFamily(family: FontFamily): thisParameters:
family: AFontFamilyobject.family: Unique name used to reference the family frommaterial.font.faces: Array ofFontFaceentries, each with:url: URL of the font file.unicodeRanges: Array of{ from, to }code point ranges (inclusive) covered by this face.
Example:
view.addFontFamily({ family: "MapFont", faces: [ { url: "/fonts/latin.woff2", unicodeRanges: [{ from: 0x0000, to: 0x024f }], }, { url: "/fonts/cjk.woff2", unicodeRanges: [{ from: 0x4e00, to: 0x9fff }], }, ],});
const source = view.addSource({ type: "geojson", url: "/cities.geojson",});
const layer = view.addLayer({ type: "vector", source, text: { font: "MapFont", },});
layer.on("featureUpdated", ({ evaluator }) => { evaluator.evaluate( ({ properties }) => { const name = properties?.["name"] as string | undefined; return { text: name ?? "", show: !!name }; }, { filters: ["name"] }, );});removeFontFamily()
Section titled “removeFontFamily()”Unregisters a previously added font family by name. Text layers that still reference the family will no longer be able to resolve it.
Returns the ThreeView instance so calls can be chained.
Syntax:
removeFontFamily(family: string): thisParameters:
family: Thefamilyname passed toaddFontFamily().
Example:
view.removeFontFamily("MapFont");setSseMultiplierRange()
Section titled “setSseMultiplierRange()”Updates the memory-pressure SSE degrade range at runtime. min is the resting multiplier applied even without budget pressure (a value greater than 1 coarsens far tiles at rest). max is the ceiling the dynamic degrade can climb to under memory pressure. The next traversal re-selects tile LODs with the new range. Setting min = max = 1 fully disables the pressure degrade.
Syntax:
setSseMultiplierRange(min: number, max: number): voidParameters:
min: Resting (base) SSE multiplier applied without budget pressuremax: Ceiling the dynamic memory-pressure degrade can climb to
Example:
// Keep far tiles slightly coarse at rest, allow degrading up to 8x under pressureview.setSseMultiplierRange(1.5, 8.0);
// Disable the memory-pressure degrade entirelyview.setSseMultiplierRange(1, 1);memoryStats()
Section titled “memoryStats()”Returns a snapshot of engine memory usage (WASM buffer bytes, GPU estimates, retained tile counts). Returns undefined before init().
Syntax:
memoryStats(): MemoryStats | undefinedReturns:
A plain MemoryStats object, or undefined before init():
type MemoryStats = { // Total bytes of tile payloads, geometry, and DEM buffers in WASM linear memory bufferTotalBytes: number; // Bytes held in the JS-side buffer store (fetched MVT pbf and worker-built // geometry that never enter WASM linear memory). Not part of bufferTotalBytes. externalBufferBytes: number; // Number of buffers tracked by the buffer store bufferCount: number; // Estimated GPU bytes (textures, geometry, render targets) gpuBytesEst: number; // CPU bytes outside the buffer store (chiefly feature-attribute tables) externalCpuBytes: number; // Reserved bytes for in-flight fetches (released when they land) reservedBytes: number; // Configured tile-cache budget; undefined when budgeting is disabled budgetBytes: number | undefined; // Cumulative count of evicted tiles evictedCount: number; // Current memory-pressure SSE multiplier (1 = no pressure) sseMultiplier: number; // Retained (deactivated but cached) tile counts per pipeline retainedVector: number; retainedTerrain: number; retainedRaster: number; retainedTiles3d: number;};Example:
const stats = view.memoryStats();if (stats) { const MB = 1024 * 1024; console.log(`WASM buffers: ${(stats.bufferTotalBytes / MB).toFixed(1)} MB`); console.log(`GPU estimate: ${(stats.gpuBytesEst / MB).toFixed(1)} MB`); console.log(`evicted: ${stats.evictedCount}, sse x${stats.sseMultiplier}`);}workerMemoryStats()
Section titled “workerMemoryStats()”Returns a snapshot of worker-side memory: per-tile-worker WASM heaps (point-in-time samples from the pool’s post-task probes. This call also requests fresh probes, whose results show up on the next call) and the font worker’s heap/cache breakdown. Returns undefined before init().
Syntax:
async workerMemoryStats(): Promise<WorkerMemoryStats | undefined>Returns:
A Promise resolving to a WorkerMemoryStats object, or undefined before init():
type WorkerMemoryStats = { // Tile-worker pool heaps (undefined per slot until first probed) tileWorkers: | { // Last probed WASM heap per slot (undefined = not probed yet) perSlot: (number | undefined)[]; // Sum of the probed heaps totalBytes: number; // The per-worker budget slots are recycled against maxWorkerHeapBytes: number; } | undefined; // Font worker heap/cache breakdown; undefined while no font is in use fontWorker: | { // Total WASM linear memory of the font worker (never shrinks) heapBytes: number; fontCount: number; atlasCount: number; glyphCount: number; // Raw font file bytes held by the cache fontBytes: number; // Monochrome (SDF/MSDF) atlas pixel bytes atlasBytes: number; // COLRv1 color atlas pixel bytes colorAtlasBytes: number; // Configured cache budget; undefined when unlimited budgetBytes?: number; } | undefined;};Example:
const stats = await view.workerMemoryStats();if (stats?.tileWorkers) { const MB = 1024 * 1024; console.log(`tile workers: ${(stats.tileWorkers.totalBytes / MB).toFixed(1)} MB`);}if (stats?.fontWorker) { console.log(`font atlas bytes: ${stats.fontWorker.atlasBytes}`);}