A JavaScript library that performs coordinate transformation between two plane coordinate systems using transformation definitions generated by Maplat. This is part of the Maplat project.
日本語のREADMEはこちら
- Import Transformation Definitions: Import and build internal structures from transformation definitions generated by Maplat
- V2/V3 Format Support: Compatible with both legacy V2 compiled format (4 fixed boundary vertices) and the new V3 format (N boundary vertices for higher accuracy)
- Bidirectional Coordinate Transformation: Convert coordinates between two planes in both directions
- Topology Preservation: Maintains homeomorphic properties during transformation
- Multiple Coordinate System Support: Handles transformations between various coordinate systems including standard orthogonal coordinates, Y-axis inverted coordinates, and distorted coordinates like bird's-eye views
- State Management: Save and restore transformation states
- Sub-map Selection (Processing 2): For maps with multiple overlapping TIN regions (
sub_maps), automatically determines which TIN to apply based on region boundaries, priority, and importance - Viewport Transformation (Processing 3): Converts a display viewport (center, zoom, rotation) in pixel coordinate space to a viewport in the map coordinate space (EPSG:3857)
- Cross-map Viewport Sync (Processing 4): Converts a display viewport from one pixel map directly to the corresponding viewport of another pixel map, via the shared map coordinate space
- Node.js: >= 20
- pnpm: >= 9 (for development)
pnpm add @maplat/transformnpm install @maplat/transform<script src="https://unpkg.com/@maplat/transform/dist/maplat_transform.umd.js"></script>import { Transform } from '@maplat/transform';
// Import transformation definition
const transform = new Transform();
transform.setCompiled(compiledData); // Apply transformation definition generated by Maplat
// Forward transformation (source → target coordinate system)
const transformed = transform.transform([100, 100], false);
// Backward transformation (target → source coordinate system)
const restored = transform.transform(transformed, true);The library may throw errors in the following cases:
- Transformation errors in strict mode
- Attempting backward transformation when not allowed
- Invalid data structure during transformation
If errors occur, the transformation definition data needs to be modified. Please use editor tools that incorporate @maplat/tin to modify transformation definitions.
When a single map image contains multiple overlapping TIN definitions (sub_maps), use MapTransform to automatically select the correct TIN and transform coordinates.
import { MapTransform } from '@maplat/transform';
const mt = new MapTransform();
mt.setMapData({
compiled: mainCompiledData, // Main TIN compiled data
sub_maps: [
{ compiled: sub0Data, priority: 1, importance: 1 },
{ compiled: sub1Data, priority: 2, importance: 2 },
],
});
// Forward: pixel XY → EPSG:3857 (returns [layerIndex, mercCoord] or false)
const result = mt.xy2MercWithLayer([320, 240]);
if (result) {
const [layerIndex, merc] = result;
console.log('layer:', layerIndex, 'merc:', merc);
}
// Reverse: EPSG:3857 → pixel XY (returns up to 2 layers, each [layerIndex, xyCoord] or undefined)
const results = mt.merc2XyWithLayer([15000000, 4000000]);
results.forEach((r, i) => {
if (r) console.log(`result ${i}: layer ${r[0]}, xy`, r[1]);
});Convert a pixel-map viewport (center position, zoom level, rotation angle) to and from a geographic viewport in EPSG:3857. The viewport is represented as five Mercator points (center + four cardinal offsets).
import { MapTransform } from '@maplat/transform';
const mt = new MapTransform();
mt.setMapData({ compiled: compiledData });
const canvasSize = [800, 600]; // [width, height] in pixels
// Pixel viewport → EPSG:3857 five points
const viewpoint = {
center: [15000000, 4000000], // EPSG:3857 center of the pixel-space viewport
zoom: 14,
rotation: 0,
};
const mercs = mt.viewpoint2Mercs(viewpoint, canvasSize);
// mercs: [[cx,cy], [north], [east], [south], [west]] (EPSG:3857)
// EPSG:3857 five points → pixel viewport
const vp = mt.mercs2Viewpoint(mercs, canvasSize);
console.log(vp.center, vp.zoom, vp.rotation);Convert the display viewport of one pixel map to the corresponding viewport of another pixel map, using the shared EPSG:3857 space as an intermediary.
import { MapTransform } from '@maplat/transform';
const mtA = new MapTransform();
mtA.setMapData({ compiled: compiledDataA });
const mtB = new MapTransform();
mtB.setMapData({ compiled: compiledDataB });
const canvasSize = [800, 600];
// Map A viewport (pixel space A)
const vpA = { center: [15000000, 4000000], zoom: 14, rotation: 0 };
// Pixel space A → EPSG:3857 five points (Processing 3 forward)
const mercs = mtA.viewpoint2Mercs(vpA, canvasSize);
// EPSG:3857 five points → Map B viewport (Processing 3 reverse)
const vpB = mtB.mercs2Viewpoint(mercs, canvasSize);
console.log('Map B viewport:', vpB);The main class for coordinate transformation.
const transform = new Transform();Import and apply a compiled transformation definition generated by Maplat. Supports legacy format, V2 (4 boundary vertices), and V3 (N boundary vertices) automatically.
- Parameters:
compiled: Compiled transformation definition object (V2, V3, or legacy format)
Perform coordinate transformation.
- Parameters:
apoint: Coordinate to transform[x, y]backward: Whether to perform backward transformation (default:false)ignoreBounds: Whether to ignore boundary checks (default:false)
- Returns: Transformed coordinate or
falseif out of bounds - Throws: Error if backward transformation is attempted when
strict_status == "strict_error"
Vertex Modes:
Transform.VERTEX_PLAIN: Standard plane coordinate systemTransform.VERTEX_BIRDEYE: Bird's-eye view coordinate system
Strict Modes:
Transform.MODE_STRICT: Strict transformation modeTransform.MODE_AUTO: Automatic mode selectionTransform.MODE_LOOSE: Loose transformation mode
Strict Status:
Transform.STATUS_STRICT: Strict statusTransform.STATUS_ERROR: Error status (backward transformation not allowed)Transform.STATUS_LOOSE: Loose status
Y-axis Modes:
Transform.YAXIS_FOLLOW: Follow Y-axis directionTransform.YAXIS_INVERT: Invert Y-axis direction
The class for sub-map selection, viewport transformation, and cross-map viewport synchronization (Processings 2–4).
const mt = new MapTransform();Load a main TIN and optional sub-map TINs.
- Parameters:
mapData:{ compiled, maxZoom?, sub_maps? }— main compiled TIN data, optional explicit maxZoom, and optional array of sub-map definitions
Transform a pixel coordinate to EPSG:3857 using the main TIN.
- Parameters:
xy— pixel coordinate[x, y] - Returns: EPSG:3857 coordinate, or
falseif out of bounds
Transform an EPSG:3857 coordinate to pixel coordinate using the main TIN (reverse).
- Parameters:
merc— EPSG:3857 coordinate[x, y] - Returns: Pixel coordinate, or
falseif out of bounds
Transform a pixel coordinate to EPSG:3857, automatically selecting the appropriate TIN from sub-maps based on priority and region (Processing 2).
- Parameters:
xy— pixel coordinate[x, y] - Returns:
[layerIndex, mercCoord]orfalseif out of bounds
Transform an EPSG:3857 coordinate to pixel coordinate across all applicable TIN layers, returning up to 2 results ordered by importance (Processing 2).
To return more than 2 layers, increase the limit in the
.slice(0, 2)/.filter(i < 2)lines inside the implementation.
- Parameters:
merc— EPSG:3857 coordinate[x, y] - Returns: Array of up to 2 elements; each is
[layerIndex, xyCoord]orundefined
Convert a pixel-space viewport to five EPSG:3857 points (Processing 3).
- Parameters:
viewpoint:{ center, zoom, rotation }— viewport in pixel space (center as EPSG:3857 equivalent viaxy2SysCoord)size: Canvas size[width, height]
- Returns: Array of 5 EPSG:3857 points
[center, north, east, south, west] - Throws: Error if the center point is outside the TIN bounds
Convert five EPSG:3857 points back to a pixel-space viewport (Processing 3 reverse).
- Parameters:
mercs: Array of 5 EPSG:3857 points (as returned byviewpoint2Mercs)size: Canvas size[width, height]
- Returns:
Viewpoint—{ center, zoom, rotation }in pixel space - Throws: Error if the center point cannot be reverse-transformed
maxxy: number—2^maxZoom × 256; the pixel-to-EPSG:3857 scale factor
PointSet,BiDirectionKey,WeightBufferBD,VertexMode,StrictMode,StrictStatus,YaxisModeCentroidBD,TinsBD,KinksBD,VerticesParamsBD,IndexedTinsBDCompiled,CompiledLegacyTins,Tri,PropertyTriKeyEdge,EdgeSet,EdgeSetLegacyViewpoint—{ center: number[], zoom: number, rotation: number }MapData—{ compiled: Compiled, maxZoom?: number, sub_maps?: SubMapData[] }SubMapData—{ compiled: Compiled, priority: number, importance: number, bounds?: number[][] }
transformArr: Low-level coordinate transformation functionrotateVerticesTriangle: Rotate vertices of a trianglecounterTri: Counter triangle utilitynormalizeEdges: Normalize edge definitions
import { format_version } from '@maplat/transform';
console.log(format_version); // Current format versionThe compiled data format has two modern versions:
- V2: Uses 4 fixed boundary vertices derived from the map bounding box
- V3: Uses N boundary vertices (≥4) for more precise boundary definition, improving transformation accuracy especially near map edges
Both formats are handled transparently by setCompiled(). V3 compiled data is generated by @maplat/tin version 3 or later.
For detailed technical information about the transformation internals, see:
- Transform Internals - Runtime notes on how Transform class reconstructs state and performs coordinate lookups
pnpm testThis library specializes in executing coordinate transformations and does not include functionality for generating or editing transformation definitions. If you need to create or edit transformation definitions, please use the @maplat/tin package.
Maplat Limited License 1.1
Copyright (c) 2025 Code for History
- Kohei Otsuka
- Code for History
We welcome your contributions! Feel free to submit issues and pull requests.