js-api
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->
Table of Contents
- normalizeAngle
- DRAW_STYLES
- ensureViewportAlignedSymbols
- useStableImageSrc
- MTA_COLORS
- useMapViewState
- useMapEvents
- ensureBaseLayers
- padAngle
- padAngle
- useSelectionController
- useCameraRotation
- buildSpriteFallbacks
- quantizeAngleTo45
- useGlobalKeymap
- generateTrainLineIcon
- useRotationControls
- quantizeAngleTo90
- ensureLayersBetweenPermitAreasAndDroppedObjects
- snapToNearest
- MTA_COLOR_CLASSES
- computeBearingDegrees
- MTA_COLOR_HEX
- pointToSegmentDistanceSq
- MTA_TEXT_COLOR_HEX
- generateFallbackIcon
- computeNearestLineBearing
- parseTrainLines
- generateIconId
- getTrainLineColor
- iconCache
- getTrainLineClasses
- getOrCreateTrainLineIcon
- addEnhancedSpritesToMap
- getTrainLineHexColor
- getTrainLineTextColor
- clearIconCache
- sortTrainLines
- preloadCommonTrainLineIcons
- groupSubwayEntrancesByLocation
- setBaseVisibility
- unload
- createStationFeature
- clearAllFeatureState
- addTrainLineIconToMap
- buildSpriteImageId
- chooseAngleQuantizer
- quantizeToSlices
- computeNearestSegmentClosestPointBearing
- computeFeatureSpriteAngle
- quantizeBearingForSprites
- computeDominantBearingFromPolygon
- computeDominantViewportBearing
normalizeAngle
Utility functions for object geometry transforms.
Parameters
deg
DRAW_STYLES
Canonical styles for Mapbox GL Draw. Standardizes on blue (#2563eb) for all features and handles. Hides point markers for features tagged as 'text' annotations.
ensureViewportAlignedSymbols
Ensure symbol layers are aligned to the viewport so icons/text do not rotate with the map. Applies a consistent set of layout properties for provided layer ids.
Parameters
maplayerIds(optional, default[])
useStableImageSrc
useStableImageSrc Given a fallback chain, keeps the last-good src until the next candidate successfully loads, then switches atomically. Prevents flicker during perspective switches.
Parameters
srcChainchangeKey
MTA_COLORS
Official MTA train line colors Based on NYC Core Framework subway icon styles
useMapViewState
useMapViewState Exposes { zoom, bearing, pitch, viewType, renderTick } for a MapLibre/Mapbox map.
- Subscribes primarily to 'render' and coalesces updates via requestAnimationFrame
- Also listens to basic camera events to ensure state updates if render is throttled
- Cleans up listeners and pending RAF on unmount or map/style changes
Parameters
map
useMapEvents
useMapEvents Centralized lifecycle for MapLibre/Mapbox map events with automatic cleanup and optional re-attachment on style reload (useful for layer-bound handlers).
handlers: { [eventName: string]: Function | { handler: Function, layerId?: string, once?: boolean } } options:
- reattachOnStyleLoad?: boolean (default: true) re-attach handlers after style reload
Parameters
maphandlers(optional, default{})options(optional, default{})
ensureBaseLayers
Ensure base source and layers exist for a geography without fetching data. Adds an empty FeatureCollection to start to avoid races with events.
Parameters
mapidPrefixstring e.g., 'permit-areas' | 'plaza-areas' | 'intersections'type("polygon"|"point")options(optional, default{})
padAngle
Utilities for enhanced isometric sprite rendering for point layers.
- Loads angle-variant PNG sprites into the map sprite registry
- Computes nearest CSCL centerline bearing for a point
- Quantizes and maps bearings to sprite variant IDs
Parameters
angle
padAngle
Pad an angle integer (0..359) to 3 digits, e.g. 0 -> "000", 45 -> "045".
Parameters
angle
useSelectionController
useSelectionController Centralizes selection hit-tests for rectangles (polygon contains) and enhanced point objects (proximity).
Args:
- map: MapLibre/Mapbox map instance
- placeableObjects: catalog array
- droppedObjects: current objects array
- isPlacementActive: boolean (skip selection when placing)
- setSelectedRectId:
(id|null)=>void - setSelectedPointId:
(id|null)=>void
Parameters
-
$0Object$0.map$0.placeableObjects$0.droppedObjects$0.isPlacementActive$0.setSelectedRectId$0.setSelectedPointId
useCameraRotation
useCameraRotation Centralize camera rotation controls:
- Q/E keyboard nudge with smooth continuous rotation (no snapping)
- rotateend leaves bearing as-is (no forced snap)
options:
- map: MapLibre/Mapbox map instance (required)
- getAreaGeometry:
() => GeoJSON geometry | null (optional) - isEnabled?: boolean (default true)
Parameters
-
$0Object (optional, default{})$0.map$0.getAreaGeometry$0.isEnabled(optional, defaulttrue)
buildSpriteFallbacks
Sprite Resolver
Central authority for enhanced-rendering sprite URLs, image preloading, and contrasting background color computation. Consumers should NOT assemble URLs manually; instead call getCandidateSrcs() and useStableImageSrc() to avoid flicker when switching between ISO/2D or when a candidate fails to load.
Fallback order (by design):
- nested current-view dir (/static/{base}/{view}/renders/{file}.png)
- nested isometric dir
- flat current-view (/static/{base}/{file}.png)
- flat isometric Note: Legacy bw sprites are NOT included for enhanced rendering layers
quantizeAngleTo45
Given a numeric angle in degrees, quantize to nearest 45-degree bucket (0..315).
Parameters
angleDeg
useGlobalKeymap
useGlobalKeymap Provide one or more key bindings with cleanup and stable descriptor. bindings: Array<{ type?: 'keydown'|'keyup', key?: string|string[], code?: string|string[], ctrl?: boolean, alt?: boolean, shift?: boolean, meta?: boolean, onEvent: (KeyboardEvent) => void, priority?: number, // higher number wins stop?: boolean, // stop after handling preventDefault?: boolean, enabled?: boolean|() => boolean }>
Parameters
bindings
generateTrainLineIcon
Generate a canvas-based icon for one or more train lines Used for MapLibre GL symbol layers Arranges icons in a grid with max 4 icons per row
Parameters
lines[Array][101]<[string][99]>Array of train line identifierssizenumber Size of each icon (default 32px) (optional, default32)spacingnumber Spacing between icons (default 3px) (optional, default3)
Returns HTMLCanvasElement Canvas element ready to be added to map
useRotationControls
useRotationControls Centralized keyboard rotation behavior.
options:
- isPlacementActive: boolean
- rotatePlacementStep:
(delta45:number)=>void - hasSelectedRect: boolean
- rotateSelectedRectBy:
(deltaDeg:number)=>void // will be called every frame while key held - hasSelectedPoint: boolean
- rotateSelectedPointBy:
(deltaDeg:number)=>void // will be called every frame while key held (continuous in 2D) - clearSelection?: ()=>void
Keyboard bindings (consistent with existing app): , . [ ]
- Rectangles: hold for continuous rotation at 90°/s
- Points (dropped objects): hold for continuous free rotation at 90°/s in 2D mode
- Placement mode: step by 45° per keypress
Parameters
options
quantizeAngleTo90
Quantize to nearest 90-degree bucket (0,90,180,270) to favor parallel/perpendicular alignment.
Parameters
angleDeg
ensureLayersBetweenPermitAreasAndDroppedObjects
Ensure provided layers are placed between permit-area layers and dropped object symbol layers. If any permit-area layer appears above dropped objects, fall back to moving target layers to the top of the stack to preserve visibility.
Parameters
maplayerIds(optional, default[])
snapToNearest
Snap an angle to the nearest increment step (default 45°). Returns a normalized angle in [0, 360).
Parameters
angleDegstep(optional, default45)
MTA_COLOR_CLASSES
Tailwind CSS classes for MTA colors
computeBearingDegrees
Compute rhumb bearing from p1 -> p2 in degrees (0=N, 90=E). Uses simple approximation suitable for small distances in NYC.
Parameters
lon1lat1lon2lat2
MTA_COLOR_HEX
Hex color values for canvas rendering
pointToSegmentDistanceSq
Compute squared distance from point P to segment AB in lon/lat space (rough metric).
Parameters
pxpyaxaybxby
MTA_TEXT_COLOR_HEX
Text colors for each background (for contrast)
generateFallbackIcon
Generate a fallback generic subway icon
Parameters
sizenumber Icon size (optional, default32)
Returns HTMLCanvasElement
computeNearestLineBearing
Given a GeoJSON Feature<Point>, and an array of GeoJSON LineString/MultiLineString features
(e.g., CSCL centerlines), compute the bearing (0..360) of the nearest segment to the point.
Returns null if no valid lines are provided.
Parameters
pointFeaturelineFeatures
parseTrainLines
Parse daytime_routes string into array of individual train lines Handles various formats from the NYC subway entrance dataset
Parameters
Returns [Array][101]<[string][99]> Array of individual train line identifiersExamples:
"1 2 3" → ['1', '2', '3']
"A C E" → ['A', 'C', 'E']
"4-5-6" → ['4', '5', '6']
"B,D,F,M" → ['B', 'D', 'F', 'M']
generateIconId
Generate a unique icon ID for a set of train lines
Parameters
lines[Array][101]<[string][99]>Array of train line identifiers
Returns string Icon ID for use with MapLibre
getTrainLineColor
Get the MTA color for a given train line
Parameters
linestring Train line identifier (e.g., '1', 'A', 'Q')
Returns string Color name
iconCache
Icon cache to avoid regenerating identical icons
getTrainLineClasses
Get Tailwind CSS classes for a train line
Parameters
linestring Train line identifier
Returns string CSS classes
getOrCreateTrainLineIcon
Get or generate a train line icon Caches results for performance
Parameters
lines[Array][101]<[string][99]>Train line identifierssizenumber Icon size (optional, default32)
Returns object { iconId, canvas }
addEnhancedSpritesToMap
Ensure a set of angle-variant PNG images are added to the map. Each sprite will be registered under an ID derived from baseName (e.g., "linknyc_090").
Parameters
mapoptions
getTrainLineHexColor
Get hex color value for a train line
Parameters
linestring Train line identifier
Returns string Hex color code
getTrainLineTextColor
Get text color (for contrast) for a train line
Parameters
linestring Train line identifier
Returns string Hex color code for text
clearIconCache
Clear the icon cache Useful for testing or memory management
sortTrainLines
Sort train lines in a logical order (numbers first, then letters)
Parameters
lines[Array][101]<[string][99]>Array of train line identifiers
Returns [Array][101]<[string][99]> Sorted array
preloadCommonTrainLineIcons
Pre-generate common train line combinations Call this when map loads to prepare frequently used icons
Parameters
groupSubwayEntrancesByLocation
Group subway entrance features by station location Combines entrances that are very close together (same station)
Parameters
features[Array][101]<[object][100]>GeoJSON featurestolerancenumber Distance tolerance in degrees (default ~10 meters) (optional, default0.0001)
Returns Map Map of location key to combined feature data
setBaseVisibility
Toggle base (non-focused) layer visibility for a geography.
Parameters
unload
Remove all base and focused layers and the source for a geography.
Parameters
mapidPrefixstring
createStationFeature
Create a consolidated feature for a station with all its train lines
Parameters
stationDataobject Data from groupSubwayEntrancesByLocation
Returns object GeoJSON feature
clearAllFeatureState
Clear all feature-state associated with a geography source. This prevents unbounded accumulation of per-feature state (e.g., hover progress).
Parameters
mapidPrefixstring
addTrainLineIconToMap
Add a train line icon to the map Generates if not already in cache
Parameters
mapobject MapLibre map instancelines[Array][101]<[string][99]>Train line identifierssizenumber Icon size (optional, default32)
Returns string Icon ID that was added
buildSpriteImageId
Build the image ID for a given quantized angle using the configured baseName. In top-down mode, includes 'TOP' to distinguish from isometric sprites.
Parameters
baseNameangleviewType
chooseAngleQuantizer
Choose an angle quantizer based on alignment preference. When aligning to CSCL centerlines, prefer parallel/perpendicular (90° bins). Otherwise, allow 45° bins for more diagonal freedom.
Parameters
preferRightAngles(optional, defaultfalse)
quantizeToSlices
Quantize an absolute angle into N uniform slices with an optional center offset. Example: slices=8, centerOffset=22.5 produces centers at 22.5, 67.5, ...
Parameters
angleDegslices(optional, default8)centerOffsetDeg(optional, default0)
computeNearestSegmentClosestPointBearing
Compute the closest segment to a point and derive a local frame:
- axisBearing:
direction of the segment (A->B) in degrees (0=N, CW+) - side: 'left' | 'right' based on sign of cross(AB, AP) in lon/lat space
- normalLeft: axisBearing - 90 (normalized)
- normalRight: axisBearing + 90 (normalized) Returns null if no valid line segments are found.
Parameters
pointFeaturelineFeatures
computeFeatureSpriteAngle
Compute final sprite angle and image id for a point feature given base axis, side, and camera.
- facingMode: 'towardStreet' | 'awayFromStreet' | undefined (when undefined, uses axis)
- Quantizes to nearest 45° bucket.
- Avoids dependency on bearingUtils to prevent circular imports by inlining orientation logic.
Parameters
-
$0Object$0.map$0.view$0.areaGeom$0.facingMode$0.baseAxisBearing(optional, default0)$0.side(optional, defaultnull)$0.spriteBase$0.slices(optional, default8)$0.centerOffsetDeg
quantizeBearingForSprites
Quantize a map bearing to the appropriate step for sprite families. When layers prefer parallel/perpendicular alignment, snap to 90°; otherwise 45°.
Parameters
bearingDegpreferRightAngles(optional, defaultfalse)
computeDominantBearingFromPolygon
Compute the dominant orientation (bearing) of a Polygon/MultiPolygon geometry. Uses length-weighted average of doubled-angle vectors so direction (0/180) is treated the same. Returns degrees in [0, 360). When invalid, returns 0.
Parameters
geometry
computeDominantViewportBearing
Compute dominant orientation (bearing) in VIEWPORT space for a Polygon/MultiPolygon. 0° = up (toward top of screen), positive clockwise. Requires map.project.
Parameters
mapgeometry