Skip to main content

Quick Start

This guide will walk you through creating your first Threebox scene. We’ll create a simple 3D sphere on a map with mouse interaction events.

Prerequisites

Complete Example

Here’s a complete working example that creates a red sphere on a map with mouse over/out events:
<!doctype html>
<html>
<head>
  <title>Threebox - Basic Sphere Example</title>
  
  <!-- Mapbox GL JS -->
  <link href="https://api.mapbox.com/mapbox-gl-js/v2.2.0/mapbox-gl.css" rel="stylesheet">
  <script src="https://api.mapbox.com/mapbox-gl-js/v2.2.0/mapbox-gl.js"></script>
  
  <!-- Threebox -->
  <script src="https://unpkg.com/threebox-plugin/dist/threebox.min.js"></script>
  <link href="https://unpkg.com/threebox-plugin/dist/threebox.css" rel="stylesheet" />
  
  <style>
    body, html {
      width: 100%;
      height: 100%;
      margin: 0;
    }
    #map {
      width: 100%;
      height: 100%;
    }
  </style>
</head>
<body>
  <div id='map'></div>

  <script>
    // Set your Mapbox access token
    mapboxgl.accessToken = 'YOUR_MAPBOX_ACCESS_TOKEN';

    // Starting location for the map and sphere
    var origin = [-122.4340, 37.7353, 1];

    // Initialize the map
    var map = new mapboxgl.Map({
      container: 'map',
      style: 'mapbox://styles/mapbox/light-v9',
      center: origin,
      zoom: 17,
      pitch: 60,
      antialias: true
    });

    map.on('style.load', function() {
      // Add a custom 3D layer
      map.addLayer({
        id: 'custom_layer',
        type: 'custom',
        renderingMode: '3d',
        onAdd: function(map, mbxContext) {
          // Initialize Threebox
          window.tb = new Threebox(
            map,
            mbxContext,
            {
              defaultLights: true,
              enableSelectingObjects: true
            }
          );

          // Create a red sphere
          var sphere = tb.sphere({
            color: 'red',
            material: 'MeshToonMaterial'
          }).setCoords(origin);
          
          // Add event listeners
          sphere.addEventListener('ObjectMouseOver', onObjectMouseOver, false);
          sphere.addEventListener('ObjectMouseOut', onObjectMouseOut, false);
          
          // Add sphere to the scene
          tb.add(sphere);
        },
        
        render: function(gl, matrix) {
          tb.update();
        }
      });
    });

    // Event handlers
    function onObjectMouseOver(e) {
      console.log("ObjectMouseOver: " + e.detail.name);
    }

    function onObjectMouseOut(e) {
      console.log("ObjectMouseOut: " + e.detail.name);
    }
  </script>
</body>
</html>

Step-by-Step Breakdown

Let’s break down the key parts of this example:
1

Initialize the Mapbox map

Create a Mapbox GL JS map with 3D perspective:
var map = new mapboxgl.Map({
  container: 'map',
  style: 'mapbox://styles/mapbox/light-v9',
  center: [-122.4340, 37.7353],
  zoom: 17,
  pitch: 60,        // Tilts the map for 3D view
  antialias: true   // Enables antialiasing for smoother 3D objects
});
The pitch property is crucial for viewing 3D objects. Values between 0-60 degrees work well.
2

Create a custom 3D layer

Add a custom layer using Mapbox’s CustomLayerInterface:
map.addLayer({
  id: 'custom_layer',
  type: 'custom',
  renderingMode: '3d',
  onAdd: function(map, mbxContext) {
    // Initialize Threebox here
  },
  render: function(gl, matrix) {
    // Update Threebox scene here
  }
});
3

Initialize Threebox

Create a Threebox instance in the onAdd callback:
window.tb = new Threebox(
  map,
  mbxContext,  // WebGL context from Mapbox
  {
    defaultLights: true,           // Adds basic lighting
    enableSelectingObjects: true   // Enables object selection
  }
);
Store the Threebox instance in window.tb to access it globally for debugging and manipulation.
4

Create and add 3D objects

Use Threebox helper methods to create 3D objects:
var sphere = tb.sphere({
  color: 'red',
  material: 'MeshToonMaterial'
}).setCoords(origin);

tb.add(sphere);
The setCoords() method positions the object at [longitude, latitude, altitude].
5

Update the scene

Call tb.update() in the render callback to sync with Mapbox:
render: function(gl, matrix) {
  tb.update();  // Must be called every frame
}
Forgetting to call tb.update() will result in objects not appearing or not moving with the map.

Adding Interactivity

Threebox provides built-in events for 3D objects:
// Mouse over event
sphere.addEventListener('ObjectMouseOver', function(e) {
  console.log('Mouse over object:', e.detail.name);
  // Change object appearance, show tooltip, etc.
}, false);

// Mouse out event
sphere.addEventListener('ObjectMouseOut', function(e) {
  console.log('Mouse out from object:', e.detail.name);
  // Reset object appearance
}, false);

// Object selected event
sphere.addEventListener('SelectedChange', function(e) {
  console.log('Object selected:', e.detail.selected);
}, false);

Loading 3D Models

Instead of simple shapes, you can load external 3D models in various formats:
var options = {
  obj: './models/soldier.glb',     // Path to your 3D model
  type: 'gltf',                     // Format: 'gltf', 'fbx', 'obj', 'dae'
  scale: 1,                         // Scale factor
  units: 'meters',                  // Units for positioning
  rotation: { x: 90, y: 0, z: 0 }   // Initial rotation in degrees
};

tb.loadObj(options, function(model) {
  model.setCoords(origin);
  model.addTooltip("My 3D Model", true);
  tb.add(model);
});
Threebox supports GLTF/GLB, FBX, OBJ/MTL, and Collada (DAE) formats. GLTF is recommended for best performance and feature support.

Common Threebox Options

Here are some useful options when initializing Threebox:
OptionTypeDefaultDescription
defaultLightsbooleanfalseAdds default scene lighting
realSunlightbooleanfalseSimulates real sun position based on time and location
enableSelectingObjectsbooleanfalseEnables object selection with mouse
enableDraggingObjectsbooleanfalseEnables dragging objects (use Shift key)
enableRotatingObjectsbooleanfalseEnables rotating objects (use Alt key)
enableTooltipsbooleanfalseShows default tooltips on objects
skybooleanfalseAdds atmospheric sky layer
terrainbooleanfalseEnables terrain layer support

Example with More Features

Here’s an enhanced version with dragging, rotation, and tooltips:
window.tb = new Threebox(
  map,
  mbxContext,
  {
    defaultLights: true,
    enableSelectingObjects: true,
    enableDraggingObjects: true,    // Enable with Shift key
    enableRotatingObjects: true,    // Enable with Alt key
    enableTooltips: true            // Show tooltips
  }
);

var sphere = tb.sphere({
  color: 'red',
  material: 'MeshToonMaterial',
  radius: 10,
  units: 'meters'
}).setCoords(origin);

sphere.addTooltip("Red Sphere", true);
tb.add(sphere);
  • Drag (translate): Select object + Shift + mouse move
  • Drag (altitude): Select object + Ctrl + mouse move
  • Rotate: Select object + Alt + mouse move

Next Steps

Now that you have a basic Threebox scene running, explore more advanced features:

Explore Examples

View 20+ examples including animations, sunlight, terrain, and more

API Documentation

Dive into the complete API reference for all methods and options

3D Models

Learn how to load and animate GLTF, FBX, and OBJ models

Animations

Create path animations and combine embedded model animations

Troubleshooting

  • Ensure tb.update() is called in the render function
  • Check that coordinates are valid [longitude, latitude, altitude]
  • Verify defaultLights: true is set (objects need lighting to be visible)
  • Check browser console for errors
  • Set pitch: 60 in the Mapbox map initialization
  • Ensure renderingMode: '3d' is set in the custom layer
  • Set enableSelectingObjects: true in Threebox options
  • Check that event listeners are attached before adding object to scene
  • Replace 'YOUR_MAPBOX_ACCESS_TOKEN' with your actual Mapbox token
  • Verify the token has the correct permissions

Build docs developers (and LLMs) love