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()可以更準確地控制縮放比例,使其與地圖比例一致。
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END