Headless engine (advanced)
Use the low-level C++ ClusterEngine when you own map rendering and only need
cluster computation, for example a custom map SDK or server-side viewport
queries in a native module.
Import from /engine:
import {
createClusterEngine,
bboxToViewport,
DEFAULT_SUPERCLUSTER_OPTIONS,
} from 'react-native-better-clustering/engine'
import { packPoints } from 'react-native-better-clustering/utils'
For GeoJSON input and supercluster-compatible helpers, prefer
Supercluster (used internally by
useClusterer). Reach for createClusterEngine() only when you
need direct buffer control.
createClusterEngine(), Supercluster.load() and Supercluster.loadAsync()
throw if the native module is missing from the app binary; the error says how to
rebuild (see Troubleshooting).
Supercluster
A GeoJSON wrapper around the engine, with the query methods of
supercluster. MapView hands it to
superClusterRef, and useClusterer returns it.
import { Supercluster } from 'react-native-better-clustering/engine'
const index = new Supercluster({ radius: 40, maxZoom: 16 })
await index.loadAsync(points) // GeoJSON point features
const clusters = index.getClusters([-180, -85, 180, 85], 2)
index.destroy()
| Member | Description |
|---|---|
new Supercluster(options?) | Takes SuperclusterOptions, read once |
load(points) | Builds the index on the JS thread. Once per instance |
loadAsync(points) | Builds the index on a background thread and resolves to the instance. Once per instance |
isLoaded | Whether the index has finished building and the instance is not destroyed |
getClusters(bbox, zoom) | Points and clusters in a [west, south, east, north] bbox at a zoom, as in supercluster; above maxZoom, every point on its own (see Above maxZoom) |
getClustersFromRegion(region, mapDimensions) | The same for a map region and its size in points, at the zoom picked with viewportTileSize. [] until loaded |
getChildren(clusterId) | A cluster's direct children |
getLeaves(clusterId, limit = 10, offset = 0) | A cluster's points, paginated. A limit of Infinity or 0 returns all |
getAllLeaves(clusterId, offset = 0) | Every point in a cluster |
getClusterExpansionZoom(clusterId) | The zoom at which a cluster splits into its children |
getClusterBounds(clusterId) | The [west, south, east, north] bbox of a cluster's points, without reading them |
getClusterExpansionRegion(clusterId) | A map region that fits a cluster's points |
destroy() | Frees the native index. Safe to call twice; later queries throw |
Cluster features also carry properties.getExpansionRegion(). The query
methods other than getClustersFromRegion throw until the index has loaded,
and every query throws after destroy(). Unlike supercluster, there is no
getTile, and load or loadAsync can be called only once per instance:
create a new one for new points.
Lifecycle
Call methods in this order:
setOptions: radius, zoom range, reducers, tile extent, etc.setPoints: binary buffer frompackPoints()(/utilsexport; must match options).build()orbuildAsync(): build the spatial index, orbuildAsyncFrom(previous)to build it from another engine's after a few points moved (see Live updates).- Query:
getClusters,getChildren,getLeaves,getClusterBounds,getClusterExpansionZoom. dispose(): free the native index when you are done (see Native memory).
setOptions or setPoints clears the index. After either call, isBuilt is
false until you run build() again.
const engine = createClusterEngine()
engine.setOptions({
radius: 40,
minPoints: 2,
minZoom: 1,
maxZoom: 20,
extent: 512,
nodeSize: 64,
reducers: [],
})
const { buffer } = packPoints([
{ latitude: 52.23, longitude: 21.01 },
{ latitude: 52.24, longitude: 21.02 },
])
engine.setPoints(buffer)
if (!engine.isBuilt) {
await engine.buildAsync() // or engine.build() for small datasets
}
const viewport = bboxToViewport([-180, -90, 180, 90], 10)
const clusters = engine.getClusters(viewport)
getClusters reads the viewport as supercluster reads a bbox: across the
antimeridian, pass the longitudes unwrapped (west: 170, east: 190) or wrapped
(west: 170, east: -170); a span of 360° or more returns the whole world, with
each feature once.
getClusterExpansionZoom(id) returns the first zoom at which the cluster has
split into its children, whichever zoom you saw it at, so "zoom to the expansion
zoom on press" always reveals the children. It returns maxZoom + 1 for a
cluster still there at maxZoom (points at the same coordinate, for example)
and for a point id.
getClusterBounds(id) returns the box { north, south, east, west } that every
leaf under the cluster spans, without the leaves: four numbers cross into JS
for a cluster of 100k points, where getLeaves would convert each point. Fit
the map to it on a cluster press. A point id spans its own point. The box uses
the coordinates the engine indexed, which clamps
latitudes beyond ±85.05° and longitudes beyond ±180°. Supercluster has the
same method, returning a [west, south, east, north] bbox, and uses it for a
cluster's getExpansionRegion().
Always guard queries with isBuilt when options or points can change between
renders:
function queryClusters(engine: ClusterEngine, viewport: Viewport) {
if (!engine.isBuilt) {
return []
}
return engine.getClusters(viewport)
}
Above maxZoom
As in supercluster, getClusters floors the zoom and clamps it to minZoom
through maxZoom + 1. At maxZoom + 1 and above it returns every point inside
the viewport on its own, so points too close to split at maxZoom still come
apart at street level, without raising maxZoom (which costs build time and
memory). Points at the same coordinate come back as separate points on top of
each other. Supercluster.getClustersFromRegion and
useClusterer pick a zoom up to maxZoom + 1 too, as
react-native-clusterer does; the bundled MapView
stops at maxZoom and spreads such clusters out instead.
Threading
buildAsync() builds on a background thread from the points and options the
engine has when you call it. Every method stays safe to call while a build is
pending:
- Queries read one complete index each. While a build is pending they
answer from the current index, or throw if
isBuiltisfalse; they never see a half-built one. setPointsandsetOptionsapply to the next build. They clearisBuiltas usual, and the pending build's index is discarded when it finishes: its promise still resolves, butisBuiltstaysfalseuntil you build again.- Overlapping builds (
buildAsync()twice, orbuild()whilebuildAsync()is pending) each settle on their own. The first to finish publishes the index; a later one of the same points and options is dropped. dispose(), or dropping the last reference to the engine, is safe mid-build: the pending build frees its index when it finishes (see Native memory).
const pending = engine.buildAsync()
engine.setPoints(nextBuffer) // the pending build is now stale
await pending
engine.isBuilt // false: build again for nextBuffer
Live updates
When a few points move among many, such as vehicles over a fixed set of
places, buildAsyncFrom(previous) builds the new index from the index of
previous, the engine built for the last update: only the clustering around
the points that moved, changed their aggregated values, were added or were
removed is done again. The points that stay must keep their order, as a list
of markers does when some move, some join at any position and some leave;
their ids may change, as packPoints() numbers points by position. With
20 of 50,000 points moving, it takes about a twentieth of the time of a build in the
core benchmark
(its update operation).
The index is the one buildAsync() builds from the same points: the same
clusters, ids, children, aggregates and expansion zooms. Only the order in which
getClusters returns a zoom's features can differ.
It builds from scratch instead, with the same result, when previous:
- is not built;
- has other options;
- clusters with
minPointsabove 2; - has more than about 1 point in 64 changed, added or removed since (points that stay but are reordered count as changed);
- or would cost more to reuse than a build, as when many points lie within one cluster radius of each other. Updates from it then build from scratch for a while before trying again.
buildAsyncFrom reads previous's index when you call it, so you can keep
querying previous while the new index builds, and dispose of it right after
the call. Before the call, previous must not be disposed: Nitro rejects a
disposed engine as an argument with an error in debug builds, and release builds
do not check it, so the result is undefined there.
const next = createClusterEngine()
next.setOptions(options) // the same options as `current`
next.setPoints(packPoints(movedPoints).buffer)
const pending = next.buildAsyncFrom(current)
// `current` keeps answering queries until `next` is ready.
await pending
NitroModules.updateMemorySize(next) // see Native memory
current.dispose()
current = next
useClusterer and MapView build each new index this way, from the one that
serves queries meanwhile.
Native memory
The index lives in native memory, which grows with the number of points (the core benchmark puts 100k points spread over the world at about 43 MB). The JS garbage collector does not see that memory, so an engine you drop is freed only when the collector happens to run, and engines discarded on every data refresh can pile up.
Call dispose() when you are done with an engine. It frees the index right
away; if a buildAsync() is still running, the index is freed as soon as that
build finishes. Any later call on the engine throws, including a second
dispose().
The garbage collector learns an engine's native size only when the engine is handed to JS, which happens while it is still empty. After a build resolves, report the real size so the collector counts it:
import { NitroModules } from 'react-native-nitro-modules'
await engine.buildAsync()
NitroModules.updateMemorySize(engine)
Call it after the build resolves, not while one is pending. Supercluster,
useClusterer and MapView do both for you: Supercluster.destroy() disposes
its engine.
Errors
Direct ClusterEngine callers get explicit failures instead of silent empty
results:
| Call | Condition | Result |
|---|---|---|
setOptions | an option outside its valid values | throws, naming the option; the previous options and index stay |
setPoints | null / wrong layout | throws |
getClusters, getChildren, getLeaves, getClusterBounds, getClusterExpansionZoom | isBuilt === false | throws |
getChildren, getLeaves, getClusterBounds, getClusterExpansionZoom | clusterId is not a 32-bit integer (NaN, Infinity, 1.5) | throws |
getLeaves | fractional limit or offset, or NaN offset | throws |
| any method or property | after dispose() | throws |
buildAsyncFrom | previous was disposed | throws in debug builds; undefined in release builds |
Invalid buffers, invalid numbers and missing build() throw with messages
prefixed ClusterEngine:. Use packPoints() for buffers and check isBuilt
after reloads.
getLeaves reads a limit of 0, a negative number, Infinity or NaN as no
limit, so supercluster's getLeaves(id, Infinity) returns every leaf. A
negative offset skips none. For an id that is a whole number but no node, such
as -1, getChildren and getLeaves return [] and getClusterBounds
returns undefined.
Types
See Types: Headless engine for
ClusterEngine, ClusterEngineOptions, Viewport, EngineClusterNode and
ClusterBounds.