Vue中Mapbox和Three.js三维物体坐标与地图视角同步
本文解决在vue项目中使用mapbox和three.js渲染三维物体时,拖动地图视角导致物体底部偏移的问题。 目标是确保三维物体始终固定在指定的地图坐标位置。

问题描述:
三维物体成功渲染在Mapbox地图上,但拖动地图时,物体底部会发生偏移,不再保持在初始经纬度位置。
解决方案:
立即学习“前端免费学习笔记(深入)”;
核心在于同步Three.js场景矩阵和Mapbox视图矩阵。需要修正物体位置,使其与Mapbox的墨卡托投影坐标系匹配,并考虑视角变化对三维物体投影的影响。
代码调整:
以下代码片段展示了render函数和calculateModelTransform函数的修改:
1. 调整render函数:
使用mapboxgl.MercatorCoordinate设置物体位置,并考虑地图视角变化。
render: (gl, matrix) => { console.log(`custom layer rendering: ${customlayer.id}`); const m = new THREE.Matrix4().fromArray(matrix); // 使用墨卡托坐标系的位置 const modelPosition = mapboxgl.MercatorCoordinate.fromLngLat([point.lng, point.lat], this.modelAltitude); const l = new THREE.Matrix4().makeTranslation(modelPosition.x, modelPosition.y, modelPosition.z) .scale(new THREE.Vector3(modelTransform.scale, -modelTransform.scale, modelTransform.scale)) // 注意Y轴缩放的负号 .multiply(new THREE.Matrix4().makeRotationFromEuler(new THREE.Euler(this.modelRotate[0], this.modelRotate[1], this.modelRotate[2]))); customLayer.camera.projectionMatrix = m.multiply(l); customLayer.renderer.resetState(); customLayer.renderer.render(customLayer.scene, customLayer.camera); customLayer.map.triggerRepaint();}
2. 调整calculateModelTransform函数:
translateZ参数设为0,确保物体底部固定在地图上。 同时,使用meterInMercatorCoordinateUnits()获取合适的缩放比例。
calculateModelTransform(point) { const modelAsMercatorCoordinate = mapboxgl.MercatorCoordinate.fromLngLat([point.lng, point.lat], this.modelAltitude); return { translateX: modelAsMercatorCoordinate.x, translateY: modelAsMercatorCoordinate.y, translateZ: 0, // 物体底部固定 rotateX: this.modelRotate[0], rotateY: this.modelRotate[1], rotateZ: this.modelRotate[2], scale: modelAsMercatorCoordinate.meterInMercatorCoordinateUnits() // 使用墨卡托单位下的米数进行缩放 };}
通过以上调整,三维物体底部将始终固定在预设的经纬度位置,无论地图视角如何变化。 请注意代码中THREE和mapboxgl的正确引用。 Y轴缩放的负号确保物体方向正确。 使用meterInMercatorCoordinateUnits()可以更准确地控制缩放比例,使其与地图比例一致。
以上就是在Vue中使用Mapbox和Three.js时,如何确保三维物体的坐标点与地图视角一致?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1503618.html
微信扫一扫
支付宝扫一扫