Integrating Three.js with Mapbox
🎯 Introduction
By the end of this article, you will be able to overlay Three.js models, particles, or custom animations on a Mapbox map and keep them correctly positioned as the map zooms, rotates, and tilts.
Mapbox GL JS handles the basemap, map camera, and geographic interactions; Three.js handles the overlaid 3D objects. This combination suits buildings, devices, vehicles, tracks, and 3D monitoring objects.
🧱 How the libraries work together
Both libraries use WebGL, but this integration should not create two independent canvases. Mapbox provides CustomLayerInterface: reuse its canvas and WebGL context in onAdd, then render the Three.js scene in render using the matrix Mapbox supplies for the current frame.
Mapbox map camera → custom layer matrix
Longitude and latitude → MercatorCoordinate
Three.js scene + model → shared Mapbox canvas
Mapbox custom layers currently require the Mercator projection. MercatorCoordinate uses a projected world width of 1 rather than meters, so scale real-world models with meterInMercatorCoordinateUnits().
🚀 Installation and map configuration
This project uses Node.js v22.0.0, mapbox-gl@3.14.0, and three@0.185.1:
pnpm add mapbox-gl@3.14.0 three@0.185.1
Enable antialias during initialization so Mapbox creates an antialiased WebGL context, and explicitly select the mercator projection:
const map = new mapboxgl.Map({
container: mapElement,
style: 'mapbox://styles/mapbox/light-v11',
center: [116.397, 39.909],
zoom: 14,
pitch: 55,
antialias: true,
projection: 'mercator',
});
🧭 Convert coordinates and transform the model
Three.js objects use their own 3D coordinates, while Mapbox locations use longitude and latitude. Convert the model's geographic position and altitude to Mercator coordinates, then prepare translation, rotation, and scale parameters:
const modelOrigin = [116.397, 39.909];
const modelAltitude = 20;
const coordinate = mapboxgl.MercatorCoordinate.fromLngLat(
modelOrigin,
modelAltitude,
);
const modelTransform = {
translateX: coordinate.x,
translateY: coordinate.y,
translateZ: coordinate.z,
rotateX: Math.PI / 2,
rotateY: 0,
rotateZ: 0,
scale: coordinate.meterInMercatorCoordinateUnits(),
};
scale converts a Three.js model measured in meters to the Mercator units used by the custom layer. The conversion varies with latitude because of Web Mercator's scale, so do not hardcode one scale for every latitude.
🛠 Create a Three.js custom layer
Here is a minimal cube layer. In a real project, replace the cube with a model loaded by GLTFLoader:
const scene = new THREE.Scene();
const camera = new THREE.Camera();
const cube = new THREE.Mesh(
new THREE.BoxGeometry(20, 20, 20),
new THREE.MeshStandardMaterial({ color: 0x44aa88 }),
);
cube.position.z = 10;
scene.add(cube);
scene.add(new THREE.HemisphereLight(0xffffff, 0x445566, 2));
const light = new THREE.DirectionalLight(0xffffff, 2);
light.position.set(0, -70, 100).normalize();
scene.add(light);
let renderer;
const customLayer = {
id: 'three-model-layer',
type: 'custom',
renderingMode: '3d',
onAdd(map, gl) {
renderer = new THREE.WebGLRenderer({
canvas: map.getCanvas(),
context: gl,
antialias: true,
});
renderer.autoClear = false;
renderer.outputColorSpace = THREE.SRGBColorSpace;
},
render(gl, matrix) {
const rotationX = new THREE.Matrix4().makeRotationAxis(
new THREE.Vector3(1, 0, 0),
modelTransform.rotateX,
);
const rotationY = new THREE.Matrix4().makeRotationAxis(
new THREE.Vector3(0, 1, 0),
modelTransform.rotateY,
);
const rotationZ = new THREE.Matrix4().makeRotationAxis(
new THREE.Vector3(0, 0, 1),
modelTransform.rotateZ,
);
const mapMatrix = new THREE.Matrix4().fromArray(matrix);
const modelMatrix = new THREE.Matrix4()
.makeTranslation(
modelTransform.translateX,
modelTransform.translateY,
modelTransform.translateZ,
)
.scale(new THREE.Vector3(
modelTransform.scale,
-modelTransform.scale,
modelTransform.scale,
))
.multiply(rotationX)
.multiply(rotationY)
.multiply(rotationZ);
camera.projectionMatrix = mapMatrix.multiply(modelMatrix);
camera.projectionMatrixInverse.copy(camera.projectionMatrix).invert();
renderer.resetState();
renderer.render(scene, camera);
map.triggerRepaint();
},
};
map.on('style.load', () => {
if (!map.getLayer(customLayer.id)) {
map.addLayer(customLayer);
}
});
Custom layers are added above the current style layers by default. To place a model below roads or labels, pass an existing layer ID:
map.addLayer(customLayer, 'waterway-label');
With Mapbox Standard, use a slot supported by the current version to position the layer near the basemap, middle content, or labels. Layer order affects whether models obscure roads, buildings, and text.
Key points to understand:
canvas: map.getCanvas()prevents Three.js from creating another canvas.context: glmakes both libraries share one WebGL context.camera.projectionMatrixuses the matrix supplied by Mapbox each frame, so this integration does not use a Three.jsPerspectiveCamera.- Negative y-axis scaling aligns Mapbox and Three.js coordinate directions.
renderer.resetState()resets shared WebGL state to avoid affecting subsequent Mapbox rendering.- Call
map.triggerRepaint()only when models or animations change; static models can rely on Mapbox's own redraws.
This demo uses a Three.js cube without an external GLB file. Configure NUXT_PUBLIC_MAPBOX_TOKEN, then drag, zoom, and tilt the map to inspect its position:
📦 Replace the cube with a glTF/GLB model
Use GLTFLoader inside onAdd to replace the cube with a model:
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
const loader = new GLTFLoader();
loader.load(
'/models/building.glb',
(gltf) => {
gltf.scene.traverse((object) => {
if (object.isMesh) {
object.castShadow = true;
object.receiveShadow = true;
}
});
scene.add(gltf.scene);
},
undefined,
(error) => console.error('Failed to load model', error),
);
Model or export assets in meters. If size, orientation, or origin differs, adjust modelTransform.scale, rotation parameters, and the model root rather than changing the map coordinate system.
The component below uses the glTF asset from Mapbox's official example. It adds the loaded model to the Three.js scene and keeps its geographic position synchronized as the map camera changes:
🪤 Common conflicts and solutions
Avoid using OrbitControls at the same time
Mapbox already handles camera rotation, zoom, and tilt. The Three.js camera only receives Mapbox's projection matrix; adding OrbitControls would make the two camera control systems override each other.
Map clicks and Three.js picking follow separate paths
Mapbox's queryRenderedFeatures() queries only features rendered through Mapbox sources and layers, not custom Three.js meshes. Read screen coordinates from a Mapbox event, convert them to NDC, then use a Three.js Raycaster to test the model.
Here, the Three.js camera projection matrix contains both Mapbox's map matrix and the model transform. Use its inverse to reconstruct a Three.js ray from screen coordinates. Calling setFromCamera() as in a standard camera example can miss objects because the camera world matrix does not include the corresponding Mapbox model transform:
const inverseProjection = camera.projectionMatrixInverse
const rayStart = new THREE.Vector3(pointer.x, pointer.y, -1)
.applyMatrix4(inverseProjection)
const rayEnd = new THREE.Vector3(pointer.x, pointer.y, 1)
.applyMatrix4(inverseProjection)
raycaster.set(
rayStart,
rayEnd.sub(rayStart).normalize(),
)
The component below converts map clicks to NDC and uses Raycaster to test cubes in the custom layer. Click a green or orange object to display its name:
Re-add the layer after switching styles
setStyle() reloads the style and may remove the old custom layer. Call map.addLayer(customLayer) in a style.load listener and use getLayer to prevent duplicates.
Do not destroy Mapbox's WebGL context during cleanup
On unmount, call map.remove() and release geometries, materials, textures, and loader references created by Three.js. Since the canvas and WebGL context belong to Mapbox and are shared, avoid operations that forcibly destroy the context.
🧾 Summary
- Mapbox handles the map camera and geographic interactions; Three.js handles custom 3D objects.
- Reuse the Mapbox canvas and WebGL context through
CustomLayerInterface. - Convert longitude and latitude with
MercatorCoordinate.fromLngLat(). - Scale models from meters to Mercator units with
meterInMercatorCoordinateUnits(). - Update the Three.js camera projection matrix from Mapbox's matrix every frame.
- Avoid simultaneous OrbitControls; use Raycaster to pick Three.js objects.
- Re-add custom layers after style changes and release Three.js resources on unmount.
❓ Questions and answers
Q1: Why does the model move with the map?
It uses the projection matrix supplied by the map each frame. When the map zooms, rotates, or tilts, Three.js redraws with the updated matrix.
Q2: Why can't I assign longitude and latitude directly to mesh.position?
Three.js positions use 3D Cartesian coordinates, while Mapbox locations use longitude and latitude. Convert them to Mercator coordinates first.
Q3: Why is negative y scaling needed?
Mapbox custom layers and Three.js use different coordinate directions. Negative y scaling aligns the two systems.
Q4: Can queryRenderedFeatures() query Three.js models?
No. Custom WebGL objects are not Mapbox source/layer features. Use Raycaster for picking.
🧪 Exercises
- Replace the cube with a GLB model and place its origin at the map center.
- Add a click handler that converts Mapbox screen coordinates to NDC, then highlights the model hit by Raycaster.
- Change the model's longitude, latitude, and altitude to observe how
MercatorCoordinateaffects its position.
// Write your code here
🎉 You can now integrate Three.js 3D content into a Mapbox map. Next, explore model animation, track playback, and property panels for 3D objects.
