在 Mapbox 中接入 Three.js
🎯 引言
学完本文,你能把 Three.js 的三维模型、粒子或自定义动画叠加到 Mapbox 地图上,并让它们跟随地图的缩放、旋转和倾斜保持正确位置。
Mapbox GL JS 负责底图、地图相机和经纬度交互,Three.js 负责地图上方的三维对象。这个组合适合展示建筑、设备、车辆、轨迹和三维监控对象。
🧱 两个库如何配合
Mapbox 和 Three.js 都使用 WebGL,但这里不应该创建两个互相独立的画布。Mapbox 提供 CustomLayerInterface,我们在 onAdd 中复用 Mapbox 的 canvas 和 WebGL 上下文,再在 render 中使用 Mapbox 当前帧传入的矩阵绘制 Three.js 场景。
Mapbox 地图相机 → custom layer 的 matrix
经纬度 → MercatorCoordinate
Three.js 场景 + 模型 → Mapbox 共享 canvas
Mapbox 的自定义图层目前要求使用 Mercator 投影。MercatorCoordinate 不是米,而是把整个投影世界的宽度当成 1,因此真实米制模型需要乘上 meterInMercatorCoordinateUnits() 进行缩放。
🚀 安装与地图配置
当前项目使用 Node.js v22.0.0、mapbox-gl@3.14.0 和 three@0.185.1:
pnpm add mapbox-gl@3.14.0 three@0.185.1
地图初始化时要打开 antialias,让 Mapbox 创建带抗锯齿的 WebGL 上下文,并明确使用 mercator 投影:
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',
});
🧭 经纬度转换和模型变换
Three.js 的对象使用自己的三维坐标,Mapbox 的地图对象使用经纬度。先把模型的经纬度和海拔转换为 Mercator 坐标,再准备平移、旋转和缩放参数:
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 的作用是把 Three.js 中以米为单位的模型,转换为 Mapbox 自定义图层使用的 Mercator 单位。纬度越高,单位换算也会随 Web Mercator 的比例变化,因此不要在所有纬度硬编码一个缩放值。
🛠 创建 Three.js 自定义图层
下面是一个最小的立方体图层。真实项目中可以把立方体替换为 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);
}
});
自定义图层默认添加在当前样式图层的上方。如果需要让模型位于道路或标签下方,可以传入已有图层的 ID:
map.addLayer(customLayer, 'waterway-label');
使用 Mapbox Standard Style 时,也可以根据当前版本支持的 slot 选择放在底图、中间内容或标签附近。图层顺序会影响模型是否遮挡道路、建筑和文字。
这里有几个必须理解的点:
canvas: map.getCanvas()表示 Three.js 不再创建新的画布。context: gl表示两个库使用同一个 WebGL 上下文。camera.projectionMatrix使用 Mapbox 每帧传入的矩阵,因此不再使用 Three.js 的PerspectiveCamera。- y 轴缩放使用负值,是为了匹配 Mapbox 与 Three.js 的坐标方向。
renderer.resetState()用于恢复共享 WebGL 状态,避免影响 Mapbox 后续绘制。- 只有在模型或动画变化时才需要
map.triggerRepaint();静态模型可以依赖地图自身重绘。
下面的演示使用一个 Three.js 立方体,不依赖外部 GLB 文件;配置 NUXT_PUBLIC_MAPBOX_TOKEN 后,可以拖动、缩放和倾斜地图观察模型位置:
📦 替换为 glTF/GLB 模型
把立方体换成模型时,在 onAdd 中使用 GLTFLoader:
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('模型加载失败', error),
);
模型自身应以米为单位建模或导出。模型的大小、朝向和原点不一致时,优先调整 modelTransform.scale、旋转参数和模型根节点,不要直接修改地图的坐标系。
下面的组件使用 Mapbox 官方示例中的 GLTF 资源,演示模型加载完成后加入 Three.js 场景,并在地图相机变化时保持地理位置同步:
🪤 常见冲突和处理方式
不要同时使用 OrbitControls
Mapbox 已经负责相机的旋转、缩放和倾斜。这里的 Three.js 相机只是接收 Mapbox 的投影矩阵,再使用 OrbitControls 会让两套相机控制逻辑互相覆盖。
地图点击和 Three.js 拾取是两条链路
Mapbox 的 queryRenderedFeatures() 只能查询 Mapbox 自己绘制的 Source/Layer,不能直接查询自定义 Three.js Mesh。需要先通过 Mapbox 事件取得屏幕坐标,再把坐标转换为 NDC,最后使用 Three.js Raycaster 检测模型。
这里的 Three.js 相机投影矩阵包含了 Mapbox 的地图矩阵和模型变换,因此拾取时要用它的逆矩阵把屏幕坐标还原成 Three.js 射线。直接调用普通相机示例中的 setFromCamera(),会因为相机世界矩阵没有对应 Mapbox 的模型变换而出现点击无命中的情况:
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(),
)
下面的组件把地图点击位置转换为 NDC,并用 Raycaster 检测自定义图层中的立方体。点击地图中的绿色或橙色对象后,组件会显示命中的对象名称:
样式切换后要重新加入图层
setStyle() 会重新加载样式,旧的自定义图层可能被清除。把 map.addLayer(customLayer) 放在 style.load 监听中,并用 getLayer 避免重复添加。
清理时不要销毁 Mapbox 的 WebGL 上下文
组件卸载时调用 map.remove(),释放 Three.js 自己创建的几何体、材质、纹理和 loader 引用即可。共享 Mapbox 的 canvas 和 WebGL 上下文,不要调用会强制销毁上下文的操作。
🧾 小节总结
- Mapbox 管地图相机和地理交互,Three.js 管自定义三维对象。
- 通过
CustomLayerInterface复用 Mapbox canvas 和 WebGL 上下文。 - 使用
MercatorCoordinate.fromLngLat()把经纬度转换为地图坐标。 - 使用
meterInMercatorCoordinateUnits()把米制模型缩放到 Mercator 单位。 - 每帧用 Mapbox 的矩阵更新 Three.js 相机投影矩阵。
- 不要同时使用 OrbitControls,拾取 Three.js 对象要使用 Raycaster。
- 样式切换后重新添加自定义图层,卸载时释放 Three.js 资源。
❓ 知识问答
Q1:为什么模型会跟着地图移动?
因为模型使用了地图每帧传入的投影矩阵,地图缩放、旋转或倾斜时,Three.js 会用新的矩阵重新绘制。
Q2:为什么不能直接把经纬度赋给 mesh.position?
Three.js 的位置是三维笛卡尔坐标,Mapbox 的位置是经纬度,必须先转换成 Mercator 坐标。
Q3:为什么需要负的 y 缩放?
Mapbox 自定义图层的坐标方向和 Three.js 的默认坐标方向不同,负 y 缩放用于匹配两套坐标系统。
Q4:Three.js 模型能被 Mapbox 的 queryRenderedFeatures() 查询吗?
不能。自定义 WebGL 图层不是 Mapbox Source/Layer,要用 Raycaster 自己完成拾取。
🧪 小练习
- 把立方体替换为一个 GLB 模型,并把模型原点放在地图中心。
- 添加一个点击事件,将 Mapbox 的屏幕坐标转换为 NDC,再使用 Raycaster 高亮命中的模型。
- 修改模型的经纬度和海拔,观察
MercatorCoordinate对位置的影响。
// 请在这里编写代码
🎉 现在你已经能把 Three.js 的三维能力接入 Mapbox 地图了。后续可以继续扩展模型动画、轨迹播放和三维对象属性面板。
