Overview
Threebox works by adding a Three.js scene to Mapbox GL JS through the CustomLayerInterface. This interface allows you to render custom 3D content using WebGL directly on the map.CustomLayerInterface
Mapbox GL JS custom layers require three key methods:id: Unique layer identifiertype: Must be'custom'renderingMode: Should be'3d'for ThreeboxonAdd(map, gl): Initialize resources when layer is addedrender(gl, matrix): Called on every frame to render contentonRemove(map, gl)(optional): Clean up resources when layer is removed
Basic Implementation
The onAdd Method
TheonAdd method is called when the layer is added to the map. This is where you:
- Create the Threebox instance
- Load 3D models
- Add objects to the scene
- Set up event listeners
Example with 3D Model Loading
The render Method
Therender method is called every frame. It must call tb.update() to:
- Update animations via
AnimationManager - Reset renderer state
- Render the Three.js scene:
renderer.render(scene, camera) - Render CSS2D labels
- Trigger repaint if
passiveRendering: false
What tb.update() Does
From the source code (Threebox.js:897-915):Multi-Layer Setup
When using multiple custom layers, enable themultiLayer option to avoid calling tb.update() in each layer:
Layer Positioning
Place custom layers in the layer stack using the optionalbeforeId parameter:
Layer Management
Toggle Layer Visibility
Set Zoom Range
Custom layers don’t natively supportminzoom and maxzoom. Use Threebox’s helper:
Remove Layer
tb.clear(layerId, true) to dispose resources before removing the layer.
Layer-Specific Objects
Assign objects to specific layers for better organization:Clear Layer Objects
Common Patterns
Pattern 1: Single Layer Application
Pattern 2: Multiple Layers (Manual)
Pattern 3: Multiple Layers (Automatic)
Style Changes
When changing map styles, custom layers and their objects are removed:Performance Considerations
Next Steps
Camera Synchronization
Learn how the camera stays synchronized between Three.js and Mapbox
Coordinate Systems
Understand coordinate conversions in Threebox