You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Mapbox地图中实现垂直于地图的柱状自定义标记?

解决Mapbox Marker垂直于地图平面(类似globe.gl柱子效果)

要让Marker像柱子一样垂直于Mapbox地图平面,核心是让标记随地图的倾斜(pitch)角度做3D旋转,保持与地面垂直。以下是具体修改方案:

1. 调整Marker配置与样式

首先修正Marker的核心参数,并调整CSS的变换原点,确保旋转时以柱子底部为中心:

const customMarker = document.createElement("div");
const backGroundColor = theme === "dark" ? "bg-white/90" : "bg-black/90";
customMarker.className = `custom-marker w-2 h-20 rounded-full ${backGroundColor}`;

if (!device.location?.longitude || !device.location?.latitude) return;

const marker = new mapboxgl.Marker({
  element: customMarker,
  pitchAlignment: "map", // 让标记对齐地图平面
  rotationAlignment: "map",
  anchor: "bottom" // 锚点设置为柱子底部,贴合地图
})
.setLngLat([device.location.longitude, device.location.latitude])
.addTo(mapRef.current!);

添加CSS样式(可放在全局样式或组件内):

.custom-marker {
  transform-origin: bottom center; /* 旋转原点固定在柱子底部中心 */
}

2. 监听地图倾斜角度,动态更新标记旋转

当地图倾斜(pitch)变化时,让标记绕X轴旋转相同角度,保持垂直于地图平面:

const map = mapRef.current!;

// 初始化时设置初始旋转角度
customMarker.style.transform = `rotateX(${map.getPitch()}deg)`;

// 监听地图倾斜结束事件,更新旋转角度
map.on('pitchend', () => {
  customMarker.style.transform = `rotateX(${map.getPitch()}deg)`;
});

// 可选:监听倾斜过程中的变化,实时更新(性能允许的话)
map.on('pitch', () => {
  customMarker.style.transform = `rotateX(${map.getPitch()}deg)`;
});

3. 移除错误的旋转设置

删除代码中多余的setRotation(45),这个设置会让标记额外旋转,破坏垂直效果。

效果说明

通过以上修改,当地图倾斜时,标记会自动绕X轴旋转对应角度,视觉上始终垂直于地图平面,和你参考的globe.gl柱子效果一致。

内容的提问来源于stack exchange,提问作者Schickli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 20:33:26