Skip to main content

Projection engine

For the responsibilities of each API and when to use it, start with the CRS and projection API guide.

Use the math.gl projection engine to convert coordinates between geographic, projected and geocentric coordinate reference systems. It supports scalar coordinates, in-place typed arrays, custom projections and loading algorithms on demand.

Choose the API that fits your application:

APIUse it when
FullProjectionEngineYou want a ready-to-use converter with all built-in projections and CRS readers.
ConfigurableProjectionEngineYou want to supply the projections, readers and grid data your application needs.
LazyProjectionEngineYou want built-in projection algorithms to load automatically when requested.
ProjectionPipelineYou need to specify the order of individual coordinate operations.

All are exported by @math.gl/geospatial/projection or its documented subpaths. Selective imports reduce the initial bundle; reuse a converter to transform many coordinates between the same pair of CRSs. See supported transformations for input limits, and independent validation for accuracy. The package has no runtime dependency on proj4js. Applications needing the upstream API can install proj4 separately.

Start with the projections you needโ€‹

Engines hold reusable configuration and create independent transforms for each CRS pair. ProjectionEngine is an interface imported from the type-only entry:

mercator-projection.ts
import type { ProjectionEngine } from "@math.gl/geospatial/projection-types";
import { ConfigurableProjectionEngine, mercator } from "@math.gl/geospatial/projection";

const engine = new ConfigurableProjectionEngine({ projections: [mercator] });
export const projection = engine.createProjection({
from: "EPSG:4326",
to: "EPSG:3857",
});
const projected = projection.project([12, 55]);
const geographic = projection.unproject(projected);
const reusableEngine: ProjectionEngine = engine;

FullProjectionEngine supplies the built-in eager catalogue and CRS readers; LazyProjectionEngine supplies descriptors whose algorithms load on demand. The package also exports a ready-made projectionEngine instance. lazyProjectionEngine is available from @math.gl/geospatial/projection-projections-lazy. All three concrete engines implement the same factory interface.

Reuse the instance for each CRS pair. Construction resolves definitions, validates parameters, and prepares the transformation; coordinate calls are synchronous. project and unproject return new arrays. The input definitions are not mutated.

Both ends of a transformation need their projected algorithms registered. For example, Web Mercator โ†’ UTM needs both mercator and universalTransverseMercator:

import {
ProjectionTransform,
mercator,
universalTransverseMercator,
} from "@math.gl/geospatial/projection";

const projection = new ProjectionTransform({
from: "EPSG:3857",
to: "EPSG:32631",
projections: [mercator, universalTransverseMercator],
});

Geographic coordinates are built into the core. Projected algorithms, including Mercator, are opt-in. Registration is local to an instance; there is no global projection registry and no automatic fallback to proj4js. To change the available algorithms, create a new instance with the new plugin set.

Retrieve a CRS descriptorโ€‹

General engines expose asynchronous getCRS(definition, options?). Retrieval resolves metadata and loads only the registered algorithms needed for the requested converter pairs. WGS84 is always included; converters requests additional source CRS strings. All returned conversion functions are synchronous:

import {lazyProjectionEngine} from '@math.gl/geospatial/projection-projections-lazy';

const crs = await lazyProjectionEngine.getCRS('+proj=eqearth +ellps=WGS84');
const position = crs.converter.WGS84.from([12, 55, 100]);
const geographic = crs.converter.WGS84.to(position);
const output = new Float64Array(3);
crs.converter.WGS84.from([12, 55, 100], output);
const normalized = crs.converter.WGS84.normalize([372, 55, 100]);
const bounds = crs.renderingBounds;
const scale = crs.getRenderingScale(position);

CRSDescriptor is exported from the root, /core, and runtime-free /types entries. Its metadata includes coordinate frame, resolved projection parameters, ellipsoid axes in metres, effective array axis order, xUnit, yUnit, and zUnit, and explicit extraction lossiness. Each unit is a {name, metersPerUnit?, degreesPerUnit?} object. Linear units include their constant metre conversion, for example {name: 'feet', metersPerUnit: 0.3048}. Angular units include their constant degree conversion, for example {name: 'degrees', degreesPerUnit: 1} or {name: 'radians', degreesPerUnit: 180 / Math.PI}. Units follow axis reordering; geocentric XYZ share linear units. A custom unit retains its linear or angular factor with the name custom. Ground-distance scales remain separate and may depend on position. The metadata-only CRSMetadata type belongs to @math.gl/geospatial/crs.

enforceAxis and mode have the same meanings as for projection construction. The WGS84 endpoint always uses longitude/latitude in degrees and ellipsoidal height in metres. Conversion retains the engine's existing datum policy; a spherical target is not implicitly treated as a rendering-sphere reinterpretation. Fourth and later components pass through. Both methods accept an optional output array or typed array and return that same storage. Omitting output allocates a new number array.

Aliases, readers, grids, and algorithm availability come from the engine. Retrieval rejects unresolved definitions, missing algorithms, and failed imports. Caller-owned structured definitions are captured before asynchronous loading. No descriptor cache or arbitrary CRS equivalence test is implied. The specialized WebMercatorProjectionEngine continues to implement the pair-transform interface only.

Generic convertersโ€‹

CRSConverter contains from, to, and normalize functions. The dictionary key identifies the source CRS; the descriptor identifies the target CRS. from converts source โ†’ target, to converts target โ†’ source, and normalize returns source coordinates adjusted for the target projection's working convention. All three accept optional output storage. Conversion does not invoke normalization automatically.

const target = await lazyProjectionEngine.getCRS('+proj=eqearth', {
converters: ['EPSG:3857']
});
const converter = target.converter['EPSG:3857'];
const projected = converter.from(mercatorPosition);
const restored = converter.to(projected);

Additional converters use direct CRS-pair transformations. Their normalization first converts the source to WGS84, applies the target's geographic working convention, and converts back to the source CRS. This requires a valid inverse at the source position. Converters and their dictionary have readonly types; request further sources through getCRS options. Source keys are the exact supplied strings; no arbitrary equivalence lookup is performed. Additional converters do not change target bounds or distance scales.

signature preserves the exact input string under default engine conventions. Different aliases, whitespace, or parameter order produce different identities. Structured input, axis enforcement, horizontal extraction, or custom engine registrations use a resolved metadata signature constructed by @math.gl/geospatial/crs. Effective conventions include engine defaults and per-request overrides. Additional requested converters do not affect identity. Consumers can use the opaque signature within fixed engine conventions. It does not fingerprint custom algorithm implementations or grid contents and cannot guarantee packed-coordinate interchangeability across engines or perform arbitrary CRS equivalence testing.

Rendering scales and projection analysisโ€‹

renderingScale is a constant triple or a position callback; getRenderingScale(position) provides one entry point for both. Horizontal factors measure WGS84 reference-surface metres per stored target-axis unit through the complete inverse transform, including CRS units, axis order and datum stages. The metric uses the WGS84 ellipsoid consistently with the converter's output, even when the target projection uses a sphere. A CRS on another body measures metres on its own ellipsoid or sphere; a semi-major axis within 0.7% of 6375 km identifies Earth, as in PROJ.

For projected CRSs, the vertical factor is an isotropic rendering sizing convention: the square root of the inverse horizontal area scale, expressed in the vertical unit. It is not an altitude conversion. Use the component unit metadata and prepared converters for physical heights. At 60ยฐ latitude, EPSG:3857 has approximately [0.501260, 0.500417, 0.500838]; converting a height of 100 metres still preserves 100. Geocentric and identity CRSs expose constant physical unit factors.

ProjectionAnalysis instead differentiates a single projection in radians and physical projected units, excluding datum and CRS axis/unit stages. Both APIs share fourth-order finite differences, step/half-step agreement checks, and reusable sampling scratch. Descriptor sampling retains the full inverse Jacobian: reciprocals of parallel and meridional scales cannot represent rotated or sheared grids. Failed sampling or unresolved derivatives return null; nonpositive computed scales raise a contract error.

The descriptor complements SpatialReference input metadata and prepared transforms. Its rendering envelope is separate from declared areaOfUse and the explicit, application-qualified ProjectionAnalysis.domain.

Normalization and boundsโ€‹

converter.WGS84.normalize(position, output?) explicitly maps WGS84 longitude into the interval centered on the destination's central meridian and clamps latitude. It preserves altitude and later components. Conversion methods do not invoke normalization. The interval follows the CRS central meridian, prime meridian, and longitude-wrap parameters.

All built-in projection types provide finite rendering bounds chosen as an appropriate rendering target. They describe a rendering policy: a useful extent for displaying the projection and constructing rendering resources such as scale textures. They do not describe the algorithm's mathematical validity domain, a complete set of convertible coordinates, or a guarantee of projection accuracy.

Do not use rectangle membership to validate coordinates. A coordinate outside the bounds remains convertible wherever the equations are defined; being inside the rectangle does not guarantee a valid conversion. The rectangle encloses the selected rendering reference surface and can include areas outside its curved boundary. Normalization explicitly maps coordinates into the rendering target, preserving altitude and later components. Conversion functions do not apply this normalization automatically.

To frame a map in selected target axes, use renderingBounds: [[minX, minY, minZ], [maxX, maxY, maxZ]] in the effective axis order and units. Use axis to select the horizontal components when height is stored first. The envelope encloses the rendering reference surface; planar reference surfaces have zero span along their height axis. Each algorithm owns its rendering extent, normalization and bounds calculation. Bounds use analytical extrema, horizon intersections, and equation-derived enclosing ranges; descriptor assembly applies target units and axis order. False offsets, ellipsoid parameters, and projection scales affect the envelope.

PROJJSON bbox and WKT2 USAGE[BBOX[...]] supply geographic area-of-use coverage. Declared coverage replaces the default geographic/projected rendering extent, allowing applications to frame a specific region. The outer CRS's coverage takes precedence over a BoundCRS source or an extracted CompoundCRS component; component coverage is inherited when the outer CRS has none. Coverage that reaches unprojectable coordinates is clipped using the projection's finite rendering policy, including Gnomonic's horizon-safe angular cap and Mercator's latitude cap. Coverage may surround an interior singularity, such as a stereographic antipode; normalization also clips that region. Clipped rendering bounds enclose the intersection of declared coverage and the finite rendering domain, including curved boundary arcs within the coverage. The transverse bounds formulas support the central meridian ยฑ30ยฐ strip; spherical Cassini bounds support the front hemisphere. Coverage beyond those limits uses the intersection with the algorithm's default rendering target, or the default target when that intersection is empty. This rendering fallback does not restrict raw conversion. areaOfUse records the declared coverage as [west, south, east, north] in Greenwich degrees; east less than west denotes an antimeridian crossing. Coverage does not restrict conversion functions. Geocentric bounds always enclose the reference ellipsoid. The package does not fetch a full EPSG registry.

Without declared coverage, built-in algorithms use these rendering policies:

Projection familyDefault rendering target
GeographicOne longitude interval and ยฑ90ยฐ latitude
Mercator, including Web MercatorOne world, latitude ยฑ85.051129ยฐ
Global cylindrical/pseudocylindrical, Bonne, Albers, equidistant conicOne world including the poles
Lambert conformal conicOne world, stopping at 60ยฐ in the hemisphere opposite the cone
Transverse Mercator and UTMCentral meridian ยฑ30ยฐ, both polar limits
Cassini, polyconicCentral meridian ยฑ30ยฐ; polyconic avoids its latitude branch boundary
Gauss-Schreiber transverse MercatorCentral meridian ยฑ30ยฐ, latitude ยฑ60ยฐ
Swiss/Hotine oblique MercatorLongitude/latitude ยฑ10ยฐ around the effective origin
New Zealand Map GridLongitude/latitude ยฑ8ยฐ around the origin
KrovakLongitude ยฑ15ยฐ, latitude ยฑ5ยฐ around the origin
Stereographic, oblique stereographicAngular distance 150ยฐ from the origin
Azimuthal equidistant, Lambert azimuthal equal areaAngular distance 179ยฐ from the origin
OrthographicVisible hemisphere
GnomonicAngular distance 80ยฐ from the origin
Geostationary, tilted perspectiveVisible domain, avoiding any tilted image-plane singularity
Quadrilateralized spherical cubeOne complete square cube face
Oblique transformationThe wrapped algorithm's domain in rotated coordinates
GeocentricReference ellipsoid's XYZ envelope
Local identityUnit reference square

Angular clamps follow the great-circle bearing from the origin. At polar centers, normalization preserves the input meridian; an exact non-polar antipode uses the northward boundary when declared coverage permits. Longitude wrapping follows central/prime meridian and longitude-wrap parameters. +over permits unrestricted longitude conversion but retains a finite rendering target.

To expose a custom algorithm through getCRS, implement getRenderingProfile(coverage?) to supply finite reference-surface bounds and an optional normalization function. Coverage is the declared Greenwich longitude/latitude rectangle in degrees, passed unchanged. Longitude endpoints lie in [-180, 180]; west > east crosses the dateline, and [-180, south, 180, north] covers all longitudes. Latitude satisfies -90 <= south <= north <= 90. With no coverage, return the algorithmโ€™s default rendering target. If coverage-specific resolution fails, descriptor retrieval uses that default while preserving the declared coverage in metadata. Ordinary coordinate conversion does not evaluate rendering bounds.

To wrap proj4js or D3 as a backend, see external projection engines for complete adapter examples.

What is pluggable?โ€‹

Opt-in authority resolutionโ€‹

Configure a CRS resolver on an engine to prepare identifiers beyond its built-in aliases. Resolution supplies the definition; the engine still validates its algorithms, datum stages, grids and storage conventions.

import {FullProjectionEngine} from '@math.gl/geospatial/projection';
import {createCRSResolver, createCRSDictionaryProvider} from '@math.gl/geospatial/crs';

const engine = new FullProjectionEngine({resolver: createCRSResolver({providers: [
createCRSDictionaryProvider({
'APP:regional': '+proj=utm +zone=31 +datum=WGS84 +units=m'
})
]})});
const transform = await engine.createProjectionAsync({to: 'APP:regional'});
transform.project([3, 0]); // approximately [500000, 0], synchronous after preparation
const crs = await engine.getCRS('APP:regional');
crs.converter.WGS84.from([3, 0]); // also synchronous

FullProjectionEngine, ConfigurableProjectionEngine and LazyProjectionEngine accept resolver. Caller aliases take precedence over built-in identifiers; registered readers retain their declared inputs. External lookup handles remaining identifiers, including unresolved endpoints of local alias chains. Full definitions and malformed syntax are not sent to a registry as a fallback. Provider errors propagate unchanged; a successful lookup can still fail with an engine-specific unsupported-operation error.

Both endpoints and additional getCRS({converters}) sources are prepared. Source coordinate order, units, height metadata and epochs retain the native engine's existing validation: resolution never makes unsupported vertical or time-dependent operations valid. Inputs are captured before asynchronous work. Resolver configuration contributes to the choice of a resolved descriptor signature, but signatures still do not fingerprint engine implementations or grid data. Keep downstream caches scoped to their engine instance.

Synchronous createProjection() never calls a resolver, including after an earlier async lookup. Reuse the prepared transform, pass a complete definition, or register a local alias. The default engine has no external resolver, network access or database dependency.

ComponentOption or APIApplication responsibility
Projection algorithmsprojectionsImport and register the algorithms needed by both CRSs
Structured CRS execution readersparsersRegister wktCRSParser and/or projJSONCRSParser when accepting those representations
Regional datum definitionsdatumCatalogsRegister the datum catalogue plugin or application-reviewed definitions
Named definitionsaliasesSupply application-specific identifiers and their CRS definitions
Horizontal datum gridsdatumGridsFetch, decode, and register the correct grid data before construction
Custom algorithmsProjectionPluginImplement the projection equations, accepted parameters, and domain validation

An alias identifies a definition; it does not load an algorithm. Built-in aliases include WGS84, Web Mercator, WGS84 UTM zones, and UPS, but there is no general EPSG lookup service or automatic network access. EPSG:32631 expands to a UTM definition and requires universalTransverseMercator. A WKT definition named โ€œUTM zone 31Nโ€ usually declares the Transverse Mercator method and requires transverseMercator. The API reference lists plugin exports and their accepted parameters.

Composition is explicit too. obliqueTransformation(mollweide) creates a rotated Mollweide plugin with its dependency supplied directly; it does not search a global catalogue for an algorithm named in the CRS.

Register regional datumsโ€‹

ProjectionTransform, LazyProjectionEngine, and normalizeCRS include only WGS84 and NAD83 and their existing aliases. Projection algorithms and datums are independent: WGS84 โ†’ Web Mercator or WGS84 UTM needs no regional datum catalogue. Converting coordinates in another named datum requires explicit per-instance registration:

import { ProjectionTransform } from "@math.gl/geospatial/projection-core";
import { datumCatalog } from "@math.gl/geospatial/projection-datums";

const projection = new ProjectionTransform({
from: "+proj=longlat +datum=OSGB36",
to: "WGS84",
datumCatalogs: [datumCatalog],
});

The plugin provides all 452 regional names and aliases from the previous built-in catalogue. It supplies ellipsoid names, Helmert parameters, and grid registration names; it supplies no grid files and performs no fetching. Importing it does not register it globally. Pass the same option to LazyProjectionEngine, normalizeCRS, or checkProjectionCompatibility. Applications may dynamically import the plugin before construction, or provide a small custom DatumCatalogPlugin with a name and datums map. Explicit +ellps, +towgs84, and grid parameters remain supported without the catalogue when no unavailable named datum is requested.

This changes the configurable engine's default supported inputs. WKT/PROJJSON readers also require registration for regional names; unknown names fail explicitly unless an explicit WKT TOWGS84 or supported BoundCRS operation supplies the shift. The default projectionEngine registers the full catalogue internally and retains its historical ellipsoid-only handling of unmatched structured datum labels.

Minimal Web Mercatorโ€‹

import {WebMercatorProjectionEngine} from '@math.gl/geospatial/projection-web-mercator';

const engine = new WebMercatorProjectionEngine();
const projection = engine.createProjection({to: 'EPSG:3857'});
const positions = new Float64Array([12, 55, 123, 7]);
projection.projectFlatSync(positions, 4);

Use this backend when only WGS84 / EPSG:4326 and EPSG:3857 are needed. Its entry point excludes CRS readers, datum transforms and grids. The engine implements the same factory and transform contracts as the full engine. Unsupported CRS definitions fail explicitly. See the engine reference.

Measured for math.gl 5.0.0-alpha.13 on October 8, 2026 with Node 24.5.0, esbuild browser ESM, ES2020 and gzip level 9: 4,066 bytes minified / 1,389 bytes gzip (4.0 / 1.4 KiB). The runtime-free /types entry retains no executable projection code. These are isolated entry-point measurements, not full application download sizes.

Tree shaking and bundle sizeโ€‹

Use named ESM imports and register a small, explicit list. The package declares sideEffects: false, and its ESM build preserves module boundaries. A bundler can remove unused projection kernels and optional readers. Type-only imports add no runtime code.

The package has no runtime dependency on proj4js; it is installed only for repository benchmarks and compatibility tests. Installing proj4 separately and importing it elsewhere in an application can retain both implementations. CommonJS consumers are supported, but the measurements below use ESM with tree shaking.

The core has a fixed cost: CRS normalization, unit/axis/datum transformation support, and the shared ellipsoid table. WGS84 and NAD83 are built in; the regional datum catalogue is retained only when registered or when using the compatibility wrapper. Adding WKT pulls in syntax parsing and structured-CRS interpretation; PROJJSON objects already provide structured input and need less reader code.

Measured October 6, 2026 for math.gl 5.0.0-alpha.13 with lean datum defaults, Node 24.5.0, esbuild, browser ESM, ES2020, minification, and gzip level 9. Each row is a separate retained bundle, not an increment or an application-wide download estimate. KiB = 1,024 bytes.

Retained functionalityMinified KiBGzip KiB
Engine core32.011.6
Engine + full datum catalogue51.918.5
Engine + Mercator34.412.3
Engine + UTM41.115.0
Engine + Mercator + WKT reader57.819.9
Engine + Mercator + PROJJSON reader45.316.0
Engine + Mercator + NTv2 decoder37.613.6
Engine + Mercator + GeoTIFF grid adapter37.613.5
Engine + Mercator + GTX decoder35.913.0
Engine + Mercator + vertical GeoTIFF adapter39.414.1
Full engine (all plugins and readers)150.651.2
Explicit operation pipeline (no projection algorithms, models or readers)43.615.6
Optional operation selector (no catalogue data or operation payloads)4.41.6
Optional deformation model + regular velocity grid7.12.9
Optional deformation model + velocity GeoTIFF adapter12.14.7
Every root export, including wrapper, readers, grids and pipelines181.161.2

Moving regional datum definitions into the plugin reduces the core from 52,183 to 32,744 minified bytes and from 18,824 to 11,859 gzip bytes: 37.3% and 37.0% respectively, using the same build settings. The full-catalogue and wrapper rows include that data explicitly.

Tranche 12A adds about 1.1 KiB minified / 0.3 KiB gzip to the core stage machinery. The grid readers and bilinear interpolation remain optional, retained only in the corresponding reader rows and all-exports row. The vertical GeoTIFF adapter adds no bytes to the core or ordinary projection bundles. Typed operation pipelines are also optional and add no bytes to these selective bundles. Exact Helmert rotations, ordinate stacks and direction-specific steps add about 3.8 KiB minified / 1.4 KiB gzip to a retained pipeline compared with tranche 12B2. Kinematic epoch/rate support adds about 3.1 KiB minified / 1.1 KiB gzip compared with 12B3, including shared-memory overlap validation. Tranche 13A adds about 0.18 KiB minified / 0.01 KiB gzip for typed epoch/coefficient storage and prepared axis/unit constants. The core and default wrapper stay unchanged. The deformation step adds about 0.7 KiB minified / 0.2 KiB gzip to a pipeline; the separate model and velocity readers are retained only when explicitly imported. See deformation models. Single-stage static Helmert buffer specialization adds about 1.35 KiB minified / 0.47 KiB gzip to a retained pipeline, without adding bytes to the core, default wrapper, operation catalogue or lazy initial/deferred imports. See the paired benchmark evidence. Kinematic single-stage buffers add another 1.06 KiB minified / 0.33 KiB gzip to a retained pipeline. They reuse scalar epoch preparation and introduce no bytes to core, wrapper, catalogue, deformation or lazy chunks. See the kinematic measurements.

All GeoTIFF rows exclude an external TIFF decoder, workers, and grid files. No row includes downloaded datum-grid data. Different bundlers, targets, compression, shared dependencies, and import patterns change these totals. The size benefit comes from selecting a subset of algorithms and optional readers. Avoid a runtime lookup such as projectionExports[name] over the entire module namespace when you want the bundler to discard unused algorithms.

To reproduce the byte counts after building the repository:

node modules/geospatial/scripts/projection/check-bundle-budget.mjs --measure

Omit --measure to enforce the checked-in size limits. Package checks also verify that selected bundles exclude unrelated kernels and the upstream runtime. See benchmarks and packaging checks for methodology and performance data.

Load less-used projections on demandโ€‹

For automatic selection, use LazyProjectionEngine. It supplies all built-in projection descriptors and imports only the algorithms needed by the source and destination CRS:

import { lazyProjectionEngine } from "@math.gl/geospatial/projection-projections-lazy";

const projection = lazyProjectionEngine.createProjection({ to: "EPSG:32631" });
const xy = await projection.project([3, 45]);

await projection.preload();
projection.projectFlatSync(new Float64Array([3, 45]));

Use this isolated entry point to keep the algorithms deferred; the package root exports eager implementations. Construction starts no imports. Coordinate methods always return promises; the explicit sync methods use the shared implementation cache after preloading. Rotated projections automatically resolve their wrapped algorithms, including different children at the two endpoints. Aliases, readers and prepared grids use the same options as ProjectionTransform; WKT/PROJJSON readers remain opt-in.

The full descriptor catalogue adds metadata to the initial bundle and lets a splitting bundler emit chunks for every built-in algorithm. Only requested algorithms are fetched at runtime. For a smaller set or custom algorithms, use ProjectionTransform with an explicit list:

Import lightweight descriptors and pass them in the same projections list as eager plugins. Descriptor imports and instance construction do not import algorithm implementations. The first coordinate operation selects the required source and destination algorithms and loads them internally:

projection-descriptor.ts
import { ProjectionTransform } from "@math.gl/geospatial/projection-core";
import { mercator } from "@math.gl/geospatial/projection-projections-merc";
import { lazyUniversalTransverseMercator } from "@math.gl/geospatial/projection-projections-lazy-utm";

export const webMercator = new ProjectionTransform({
to: "EPSG:3857",
projections: [mercator],
});
export const utm31 = new ProjectionTransform({
to: "EPSG:32631",
projections: [mercator, lazyUniversalTransverseMercator],
});

const xy = await utm31.project([3, 45]); // Loads UTM automatically; no manual import.
const lonLat = await utm31.unproject(xy);

Instances configured only with eager plugins retain synchronous coordinate methods. Instances configured with descriptors return promises from project, unproject, projectFlat and unprojectFlat, including after loading. TypeScript infers the return shape from the supplied list. Await a batch operation before reading, changing or reusing its typed-array buffer. Scalar inputs are captured when the method is called.

Explicit synchronous methods never start imports. Preload the descriptor or instance before using them; they throw a clear error if a required algorithm is not cached:

await lazyUniversalTransverseMercator.preload(); // Optional application warm-up.
const xySync = utm31.projectSync([3, 45]);
utm31.projectFlatSync(new Float64Array([3, 45]));
// Alternatively: await utm31.preload() loads and prepares both ends of this CRS pair.

A shared cache, keyed by descriptor identity, holds pending imports and loaded implementations across instances and ESM/CommonJS entry points. Concurrent requests share a load. Failures propagate to the coordinate call and can be retried. Unused descriptors are not loaded. Separate descriptors with the same name are not conflated. preloadProjection(descriptor) also warms the cache, and getLoadedProjection reads it without loading anything. ProjectionTransform.create(options) is an optional async factory returning a fully prepared instance with synchronous coordinate methods.

Every named projection has a descriptor at projections/lazy/<id> (for example, lazyMercator and lazyUniversalTransverseMercator). The projections/lazy barrel exports them all. Composite projections use lazyObliqueTransformation(lazyMollweide) or lazyObliqueTransformation('longlat'). Custom descriptors can use createProjectionDescriptor({name, aliases}, async () => plugin). These descriptors defer algorithm code; CRS definitions and grid files remain application inputs.

Optional WKT interpretation can also be deferred. The adapter uses isolated @math.gl/geospatial/crs syntax entry points so its parser stays on the lazy side:

import { ProjectionTransform } from "@math.gl/geospatial/projection-core";
import { mercator } from "@math.gl/geospatial/projection-projections-merc";

export async function loadMercatorWKT(to: string) {
const { wktCRSParser } = await import("@math.gl/geospatial/projection-parsers-wkt");
return new ProjectionTransform({
to,
projections: [mercator],
parsers: [wktCRSParser],
});
}

The definition must select an algorithm supplied in projections. The WKT reader does not download plugins, definitions or grids for an arbitrary EPSG code. Register the optional readers for the CRS representations your application accepts.

Public subpathsโ€‹

All paths below have the @math.gl/geospatial/projection/ prefix and support ESM, CommonJS and types. The native and experimental paths alias the configurable engine.

SubpathExports
operationsOptional OperationCatalog and selection metadata/diagnostics; no database or execution code
analysisProjectionAnalysis, reusable factors/Jacobians and explicit mathematical domain enforcement
bulkProjectionBuffer for separate, strided, column and chunked buffers; no projection algorithms/readers
pipelineProjectionPipeline and typed explicit operation contracts; no catalogue/readers
typesRuntime-free ProjectionEngine, Projection, PreparedProjection and shared contracts
web-mercatorMinimal WebMercatorProjectionEngine with no CRS reader, grid or datum dependencies
coreEngine, normalization, capability checks, descriptor/cache utilities, shared types and errors
projections/lazy/<id>Lightweight projection descriptors; defer algorithm imports
projections/lazyLazyProjectionEngine, descriptors and the oblique descriptor factory
projections/<id>One plugin or factory, using its existing export name
parsers/wktwktCRSParser
parsers/projjsonprojJSONCRSParser
grids/ntv2parseNTv2Grid and its options type
grids/geotiffloadGeoTIFFGrid and adapter types; excludes a TIFF decoder

Projection IDs follow their canonical PROJ names:

aea, aeqd, bonne, cass, cea, eck6, eqc, eqearth, equi, eqdc, etmerc,
geocent, geos, gnom, gstmerc, krovak, laea, lcc, merc, mill, moll,
nzmg, ob_tran, omerc, ortho, poly, qsc, robin, sinu, somerc, stere,
sterea, tmerc, tpers, utm, vandg

For example, merc exports mercator, utm exports universalTransverseMercator, and ob_tran exports the obliqueTransformation(wrappedPlugin) factory. Supply a wrapped projection explicitly, including when both plugins are dynamically imported. Geographic coordinates need no plugin; the internal Gauss helper is not a public projection. Import public subpaths rather than private src or dist files.

Measured split bundlesโ€‹

Enable ESM code splitting in the bundler. CI verifies the transitive initial static graph contains neither the deferred algorithms nor optional WKT syntax, then executes the emitted chunks. The measurements below start with an eager core and Mercator. Sizes are sums across the relevant emitted files, with gzip applied to each file.

Deferred featureInitial minified / gzip KiBAdditional minified / gzip KiB
Automatic catalogue (LazyProjectionEngine)42.0 / 15.977.5 / 36.5
UTM descriptor34.9 / 13.07.9 / 3.4
WKT reader and syntax34.8 / 12.923.4 / 8.1
Rotated Mollweide (factory plus wrapped plugin)34.9 / 12.95.3 / 2.5

The catalogue row sums all available deferred algorithm chunks, not the download for its first UTM operation. Other rows retain only their selected feature.

These are esbuild browser/ES2020 measurements, not universal chunk sizes. Bundlers may extract shared helpers, so one plugin does not necessarily mean one file. Loading all features eventually pays for all retained code and chunk overhead. CommonJS subpaths select APIs but do not provide this browser download guarantee.

Reproduce and enforce the split-bundle budgets after building:

node modules/geospatial/scripts/projection/check-lazy-package.mjs

Keep imports on the isolated subpaths throughout the eager and lazy features. Mixing in eager imports from the full @math.gl/geospatial/projection or @math.gl/geospatial/crs barrels can cause a bundler to hoist otherwise lazy code. A direct await import('@math.gl/geospatial/projection') can retain the entire catalogue; it does not mean โ€œonly UTM.โ€ Inspect the application's chunk graph, not just the presence of an import() expression. Tree shaking and deferred loading remain distinct: the former removes unused code, while the latter postpones code that is used.

Work with @math.gl/geospatial/crsโ€‹

@math.gl/geospatial/crs owns CRS definitions, WKT syntax parsing, PROJJSON types, and SpatialReference metadata. The optional execution readers turn supported definitions into parameters for this engine. Being valid WKT or PROJJSON does not guarantee that its coordinate operation is implemented.

import type { ReadonlyCRSDefinition } from "@math.gl/geospatial/crs";
import {
ProjectionTransform,
mercator,
transverseMercator,
wktCRSParser,
projJSONCRSParser,
} from "@math.gl/geospatial/projection";

export function createMapProjection(from: ReadonlyCRSDefinition) {
return new ProjectionTransform({
from,
to: "EPSG:3857",
projections: [mercator, transverseMercator],
parsers: [wktCRSParser, projJSONCRSParser],
});
}

This example accepts supported geographic/Mercator/Transverse Mercator definitions; other projected methods need their corresponding plugins. Pass PROJJSON as an object, not serialized JSON text. CRSReference and SpatialReference are also accepted by the constructor. Stored coordinate order is honored; declared axis order is optional through enforceAxis. See the CRS integration reference for height, units, provenance, compound CRSs, and horizontal extraction.

checkProjectionCompatibility(definition, options) reports whether a CRS can be constructed with the exact plugins, readers, and grids supplied. A successful check is not an accuracy certificate or a guarantee that every coordinate is inside the projection's domain or a grid's coverage. Validate the CRS and coordinate region that your application actually uses.

Load datum-grid data separatelyโ€‹

Projection code and datum-grid data have separate lifecycles. Fetch grid files and decode them before creating an instance; coordinate transforms then stay synchronous. The application chooses the grid source, caching, and error handling.

grid-projection.ts
import { ProjectionTransform, parseNTv2Grid } from "@math.gl/geospatial/projection";

export async function createGridProjection(url: string) {
const response = await fetch(url);
if (!response.ok)
throw new Error("Could not load datum grid: " + response.status);
const grid = parseNTv2Grid(await response.arrayBuffer());
return new ProjectionTransform({
from: "+proj=longlat +ellps=clrk66 +nadgrids=regional.gsb",
to: "EPSG:4326",
datumGrids: { "regional.gsb": grid },
});
}

Use a grid intended for the declared source ellipsoid and datum transformation; regional.gsb is a registration key, not a built-in dataset. The engine performs no implicit fetches. Reuse prepared grids and projection instances for multiple batches.

For supported horizontal GeoTIFF grids, loadGeoTIFFGrid(decodedTIFF) prepares the object returned by a separately chosen TIFF reader. The adapter imports no TIFF library. That reader and its workers have their own bundle costs and can also be loaded on demand. See datum grids for band conventions, ownership, coverage, and inverse-edge behavior. Explicit vertical height conversion is described below; time-dependent operations use the explicit pipeline API.

Convert geoid heightsโ€‹

Register a prepared VerticalGrid under the name used by +geoidgrids. A source grid converts gravity-related height H to ellipsoidal height h using h = H + N; a destination grid applies H = h - N. The supplied offsets N are geoid undulations in metres. Source conversion runs before the horizontal datum transformation; destination conversion runs after it. Each grid is sampled in its own CRS's horizontal datum, at Greenwich longitude and geographic latitude. These are explicit stages following PROJ's vertical-grid convention.

import { ProjectionTransform } from "@math.gl/geospatial/projection-core";
import { parseGTXGrid } from "@math.gl/geospatial/projection-grids-gtx";

const response = await fetch("/grids/local.gtx");
if (!response.ok) throw new Error("Could not load vertical grid");
const local = parseGTXGrid(await response.arrayBuffer());
const projection = new ProjectionTransform({
from: "+proj=longlat +datum=WGS84 +geoidgrids=local",
to: "EPSG:4979",
verticalGrids: { local },
});
const positions = new Float64Array([12, 41, 100, 7]);
projection.projectFlat(positions, 4); // height changes; measure 7 is preserved

Choose a model whose horizontal datum, vertical datum, tide convention and area of use match your data. The key local is an application registration name, not an EPSG vertical CRS or an automatically selected model. An ellipsoid alone does not enable a horizontal datum shift: declare the datum or explicit +towgs84 parameters when a shift is needed.

ProjectionTransform and the full and lazy engines accept the same verticalGrids map. Load grid data before constructing the projection. Lazy projection algorithms can still preload separately. No file, network request, TIFF decoder or geoid model is imported implicitly. The optional readers can themselves be dynamically imported.

For an already loaded @math.gl/earth model, use the structural adapter:

import { createGeoidGrid } from "@math.gl/geospatial/projection-grids-vertical";

// geoid is a previously prepared @math.gl/earth Geoid instance.
const verticalGrids = { local: createGeoidGrid(geoid) };

The adapter calls getHeight(latitudeDegrees, longitudeDegrees) and retains the model's interpolation and ownership rules. It adds no runtime dependency on @math.gl/earth. createVerticalGrid({origin, step, size, offsets, noData}) instead snapshots a regular bilinear grid. Origin and positive spacing are degrees; rows run south to north and columns west to east. parseGTXGrid(ArrayBuffer) snapshots big-endian float32 metre offsets from the GTX format. Its conventional -88.8888 sentinel, non-finite nodes, and values outside ยฑ1000 metres are treated as nodata, consistent with PROJ's GTX reader.

Both snapshot readers include the outer nodes and do not extrapolate. Longitudes can be expressed in equivalent 360-degree turns, including bounded grids crossing the antimeridian. A missing global seam cell is not synthesized; the grid must cover the requested coordinate. A nodata corner with nonzero interpolation weight makes that sample uncovered. Ordered +geoidgrids=regional,global lists try the first covering grid. Prefix an optional registration with @; use an explicit final null for a zero-offset fallback. Missing required registrations fail construction; uncovered coordinates and non-finite custom offsets throw during transformation.

Vertical transformations require XYZ or XYZM, including flat arrays; M and later ordinates remain measures. +vunits/+vto_meter and requested axes are applied around the metre-based height stage. A failing flat record is left unchanged along with all later records; earlier records may have completed. A vertical grid cannot be attached to a geocentric or identity CRS or combined with lossy horizontal extraction.

This is the explicit vertical-grid subset (tranches 12A/12B1). Compound/vertical WKT or PROJJSON execution, dynamic datum interpretation and automatic EPSG operation lookup remain outside the supported subset. Optional operation selection filters application-reviewed candidates. Explicit typed pipelines and coordinate epochs are available through the optional pipeline API.

Vertical GeoTIFF geoid modelsโ€‹

loadVerticalGeoTIFFGrid prepares the geoid subset of PROJ Geodetic TIFF Grids. Use it for modern GeoTIFF geoid models; loadGeoTIFFGrid remains the separate adapter for horizontal latitude/longitude shifts. Both receive a decoded TIFF object and import no TIFF decoder. Fetching, compression and worker choices belong to the application.

The reader also accepts a plain VerticalGridGeoTIFFData dataset, structurally compatible with loaders.gl's GeoTIFFRasterLoader output. Pass the decoded dataset directly to loadVerticalGeoTIFFGrid(dataset). It preserves original band indices, so band zero must be included. Image order, unscaled samples, per-image/per-band GDAL metadata, GeoKeys, nodata and geometry tags have the same validation as the geotiff.js input. No runtime dependency on loaders.gl is added.

import { ProjectionTransform } from "@math.gl/geospatial/projection-core";
import { loadVerticalGeoTIFFGrid } from "@math.gl/geospatial/projection-grids-vertical-geotiff";
import { fromArrayBuffer } from "geotiff"; // separately installed, application-owned decoder

const response = await fetch("/grids/local-geoid.tif");
if (!response.ok) throw new Error("Could not load geoid grid");
const geoid = await loadVerticalGeoTIFFGrid(
await fromArrayBuffer(await response.arrayBuffer()),
);
const projection = new ProjectionTransform({
from: "+proj=longlat +datum=WGS84 +geoidgrids=geoid",
to: "EPSG:4979",
verticalGrids: { geoid },
});
projection.project([12, 41, 100]); // synchronous after grid preparation

The adapter requires geographic degree coordinates, explicit PixelIsPoint or PixelIsArea, positive north-up pixel spacing, and one tiepoint. PixelIsArea is shifted to cell centres; nonzero tiepoint pixel indices are honored. Explicit non-Greenwich prime meridians, rotated/projected rasters, overviews and masks are rejected. It does not transform or resolve the interpolation CRS: the application must verify the file's geographic datum and longitude reference match the CRS supplied to the projection.

Dataset metadata must declare TYPE=VERTICAL_OFFSET_GEOGRAPHIC_TO_VERTICAL, and band zero must declare DESCRIPTION=geoid_undulation. Its unit must be metre (also the default if absent). Raw nodata is compared in the decoded band precision (including float32 rounding) before raw * SCALE + OFFSET; absent scale and offset default to 1 and 0. Only band zero is decoded, so optional uncertainty bands are excluded. Horizontal, velocity, ellipsoidal-height-offset and vertical-to-vertical grids are rejected, as are requested non-bilinear interpolation and non-metre bands.

Prepared offsets are copied. TIFF objects and decoded arrays can be released after loading. Multiple images must be ordered parent before nested child, or have disjoint interiors; later images take precedence, including on a shared edge. A child's uncovered or nodata sample falls back to an earlier covering image. This is an explicit fallback policy, not a promise of matching every PROJ subgrid-selection edge case. Bounded antimeridian grids use equivalent longitudes; no missing seam cells are synthesized.

Independent tests decode seven small authored files using geotiff and compare with PROJ 9.5.1: point/area registration, Deflate, big-endian scaled int16, nonzero tiepoints, nested grids, nodata and antimeridian sampling. See validation for scope. The adapter and decoder can both be dynamically imported; normal core and projection bundles do not retain this reader.

Transform flat buffers in placeโ€‹

Use projectFlat and unprojectFlat for interleaved coordinate buffers:

import { ProjectionTransform, mercator } from "@math.gl/geospatial/projection";

const projection = new ProjectionTransform({
to: "EPSG:3857",
projections: [mercator],
});
const positions = new Float64Array([12, 55, 13, 56]);
projection.projectFlat(positions, 2); // returns the same view
projection.unprojectFlat(positions, 2);

const vertices = new Float64Array([12, 55, 100, 7, 13, 56, 200, 8]);
projection.projectFlat(vertices, 4); // XYZM: transforms XYZ, preserves M

The record width must be an integer at least 2 that divides the view length. Float32Array is supported, with Float32 storage precision; Float64 is preferable when large projected coordinates must retain small differences. Use a subarray view to transform a selected range. Geocentric transformations require at least three components per record.

Built-in batch operations reuse a mutable point instead of making temporary JavaScript coordinate arrays for every record. This does not guarantee zero heap allocation, and custom scalar plugins can allocate. Calls are synchronous and do not yield to the UI; schedule large jobs in a worker if the application needs that. A coordinate error stops the batch after any earlier records have been transformed. Copy the input first if the operation must be atomic. See the flat-array contract for exact failure and dimension behavior.

Batch performanceโ€‹

Common projections automatically use bulk operations where the CRS pair permits it. Use projectFlat for large buffers and reuse the converter; no extra application configuration is needed. Datum, grid and axis operations retain the same coordinate and precision guarantees. Custom plugin authors can supply whole-buffer hooks.

Add a custom projectionโ€‹

Implement ProjectionPlugin and register it like a built-in plugin. The following minimal spherical cylindrical example illustrates the contract; it intentionally supports no origin, scale, or offset parameters:

custom-projection.ts
import type { ProjectionPlugin } from "@math.gl/geospatial/projection";

export const simpleCylindrical: ProjectionPlugin = {
name: "simple_cylindrical",
parameters: [],
create({ semiMajorAxis: radius, eccentricitySquared, primeMeridian = 0 }) {
if (eccentricitySquared !== 0)
throw new Error("This plugin requires a sphere");
return {
getRenderingProfile(coverage) {
const radians = Math.PI / 180;
const [west, south, east, north] = coverage ?? [-180, -90, 180, 90];
const wrap = (longitude: number) =>
((longitude + 180) % 360 + 360) % 360 - 180;
// A single projected rectangle encloses both sides of wrapped coverage.
const left = west > east || west === 180 ? -180 : west;
const right = west > east || east === -180 ? 180 : east;
return {
bounds: [
[radius * (left * radians - primeMeridian), radius * south * radians, 0],
[radius * (right * radians - primeMeridian), radius * north * radians, 0],
],
normalize(point) {
let longitude = wrap(point.x);
const inside = west <= east
? longitude >= west && longitude <= east
: longitude >= west || longitude <= east;
if (!inside) {
longitude = Math.abs(wrap(longitude - west)) <= Math.abs(wrap(longitude - east))
? west : east;
}
point.x = longitude;
point.y = Math.max(south, Math.min(north, point.y));
},
};
},
forward: (longitude, latitude) => [radius * longitude, radius * latitude],
inverse: (x, y) => [x / radius, y / radius],
forwardInPlace(point) {
point.x *= radius;
point.y *= radius;
},
inverseInPlace(point) {
point.x /= radius;
point.y /= radius;
},
};
},
};

Use it with projections: [simpleCylindrical] and, for example, to: '+proj=simple_cylindrical +R=6371000 +datum=none'. The plugin receives longitude/latitude in radians and produces projected meters. The engine handles external CRS units, axis order, datum operations, and height. A plugin handles its own declared projection parameters, including any false offsets it chooses to support, and must reject unsupported values and singularities.

Mutable hooks must preserve Z for horizontal projections, update synchronously, and never retain the caller's scratch point. Scalar methods remain required for compatibility. Duplicate names or aliases are rejected; importing or constructing a plugin does not register it globally. See the plugin API for the full contract.

Compatibility and provenanceโ€‹

The projection engine includes algorithms adapted from proj4js and PROJ, as well as original math.gl code. Source comments and distributed notices identify their origins. The package includes MIT attribution and the Apache-2.0 notice retained by Equal Earth.

The nine remaining upstream-corpus differences are deliberate strict-input rejections, dispositioned individually. Cardinal polar-axis mappings are supported; arbitrary axis rotations remain outside the subset. Broader grid coverage, independent accuracy references, and regional projection validity limits still need qualification. Keep any fallback to a separately installed proj4 runtime an explicit application decision: it adds another implementation with different dimension and validation behavior. The roadmap, audit, and API reference describe those boundaries.

For separate output buffers, padded records or X/Y/Z/M columns, see reusable coordinate buffers. The optional /bulk adapter keeps the supplied projection's CRS and epoch behavior and requires lazy projections to have completed preload() before synchronous coordinate calls.