js-api
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->
Table of Contents
- normalizeAngle
- DRAW_STYLES
- ensureViewportAlignedSymbols
- SAFETY_CONSTANTS
- useStableImageSrc
- useTutorialProgress
- MTA_COLORS
- autoDetectPedestrianDemand
- loadOpenStreetsData
- useMapEvents
- useMapViewState
- ensureBaseLayers
- padAngle
- padAngle
- useSelectionController
- useCameraRotation
- buildSpriteFallbacks
- quantizeAngleTo45
- useGlobalKeymap
- generateTrainLineIcon
- useRotationControls
- formatDate
- quantizeAngleTo90
- ensureLayersBetweenPermitAreasAndDroppedObjects
- analyzeSidewalkClearPath
- snapToNearest
- MTA_COLOR_CLASSES
- buildHoverContent
- computeBearingDegrees
- MTA_COLOR_HEX
- isObstructingPointClearance
- pointToSegmentDistanceSq
- MTA_TEXT_COLOR_HEX
- checkIfActiveToday
- isObstructingLanePath
- generateFallbackIcon
- buildClickContent
- computeNearestLineBearing
- parseTrainLines
- isObstructingLane
- analyzeTurnRadii
- generateIconId
- getTrainLineColor
- iconCache
- getTrainLineClasses
- getOrCreateTrainLineIcon
- addEnhancedSpritesToMap
- getTrainLineHexColor
- getTrainLineTextColor
- generateSweptPath
- clearIconCache
- sortTrainLines
- preloadCommonTrainLineIcons
- isObstructingOpenStreet
- groupSubwayEntrancesByLocation
- setBaseVisibility
- formatTime
- 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[])
SAFETY_CONSTANTS
SAPO Safety Constants
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
useTutorialProgress
Hook to monitor user actions and validate tutorial steps. This acts as the 'interactivity engine' for the tutorial.
Parameters
-
map -
$1Object$1.permitAreas$1.openStreets$1.clickToPlace$1.layers$1.complianceStatus$1.selectedNodes$1.previewActive
MTA_COLORS
Official MTA train line colors Based on NYC Core Framework subway icon styles
autoDetectPedestrianDemand
Fetch and analyze pedestrian demand for a set of coordinates.
Parameters
Returns [Promise][133]<{category: [string][134], rank: [number][132], clearPathFt: [number][132]}>
loadOpenStreetsData
Fetch and normalize Open Streets data for a given bounding box.
Parameters
Returns [Promise][133]<[Object][130]> GeoJSON FeatureCollection
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{})
useMapViewState
useMapViewState Exposes { zoom, bearing, pitch, viewType, renderTick } for a MapLibre/Mapbox map.
PERFORMANCE OPTIMIZATION:
- Uses coarse bearing thresholds (1°) to reduce state updates during rotation
- Schedules updates via requestAnimationFrame to batch with browser paint
- Avoids triggering React re-renders on every frame during continuous rotation
Parameters
map
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][131]<[string][134]>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
formatDate
Format a date string (ISO or timestamp) to a readable format
Parameters
dateStr
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[])
analyzeSidewalkClearPath
Check if a feature obstructs a clear path on a sidewalk.
Parameters
sidewalkFeatureFeature The sidewalk polygonobjectFeatureFeature The user-placed objectrequiredClearPathFtnumber Required clear path width in feet
Returns Object { isObstructed: boolean, remainingWidthFt: number }
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
buildHoverContent
Build HTML content for hover tooltip (brief)
Parameters
props
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
isObstructingPointClearance
Check if a feature obstructs a buffer around a point (e.g. hydrant).
Parameters
pointFeatureFeature The infrastructure point (e.g. hydrant)objectFeatureFeature The user-placed objectclearanceFtnumber Required clearance in feet
Returns boolean
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)
checkIfActiveToday
Helper to check if an Open Street is active today based on its schedule.
Parameters
propsObject Feature properties
Returns boolean
isObstructingLanePath
Check if a feature obstructs a lane (e.g. bike lane).
Parameters
laneFeatureFeature The infrastructure line/polygon (e.g. bike lane)objectFeatureFeature The user-placed objectrequiredWidthFtnumber Required clear path width in feet
Returns boolean
generateFallbackIcon
Generate a fallback generic subway icon
Parameters
sizenumber Icon size (optional, default32)
Returns HTMLCanvasElement
buildClickContent
Build HTML content for click popup (detailed)
Parameters
props
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][131]<[string][134]> 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']
isObstructingLane
Check if a feature obstructs the emergency lane.
Parameters
laneFeature The 15ft wide emergency lane geometry (Polygon)featureFeature The object geometry to check
Returns boolean
analyzeTurnRadii
Perform a swept-path analysis along a path. Checks for sharp turns that a design vehicle cannot navigate.
Parameters
Returns Object { isValid: boolean, issues: Array<{coord: number[], message: string}> }
generateIconId
Generate a unique icon ID for a set of train lines
Parameters
lines[Array][131]<[string][134]>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][131]<[string][134]>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
generateSweptPath
Perform a swept-path analysis along a path. In a simplified version, this ensures that a 10ft wide envelope can traverse the path without hitting any obstructions OR exceeding the 15ft lane boundary.
Parameters
centerlineFeature The centerline of the zone (LineString)analysisWidthFtnumber Total width to check (default 10ft) (optional, defaultSAFETY_CONSTANTS.ANALYSIS_WIDTH_FT)
Returns Feature The swept path envelope (Polygon)
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][131]<[string][134]>Array of train line identifiers
Returns [Array][131]<[string][134]> Sorted array
preloadCommonTrainLineIcons
Pre-generate common train line combinations Call this when map loads to prepare frequently used icons
Parameters
isObstructingOpenStreet
Check if a feature obstructs an Open Street segment.
Parameters
openStreetFeatureFeature The Open Street line segmentobjectFeatureFeature The user-placed object
Returns boolean
groupSubwayEntrancesByLocation
Group subway entrance features by station location Combines entrances that are very close together (same station)
Parameters
features[Array][131]<[object][130]>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
formatTime
Format time string (HH:MM:SS -> h:mm AM/PM)
Parameters
timeStr
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][131]<[string][134]>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