代码
import {
BaiduMapConfig,
BaiduVectorTileProvider,
Engine,
GeoInstancedMesh,
GeoJSONDataSource,
gltfLoader,
urlUtils,
} from '@baidumap/mapv-three';
BaiduMapConfig.ak = '您的密钥';
const container = document.getElementById('map');
const aspect = container.clientWidth / container.clientHeight;
const center = [116.392, 40.0347];
const engine = new Engine(container, {
map: {
projection: 'EPSG:3857',
center,
range: 600 / Math.min(1, aspect),
pitch: 60,
heading: 20,
provider: new BaiduVectorTileProvider({
displayOptions: {
building: false,
poi: false,
},
}),
},
rendering: {},
});
// 按固定角度序列在草坪上排布 300 个点,保证每次打开效果一致。
const features = Array.from({length: 300}, (_, index) => {
const angle = index * 2.399963;
const radius = 0.0026 * Math.sqrt((index + 0.5) / 300);
return {
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [
center[0] + Math.cos(angle) * radius,
center[1] + Math.sin(angle) * radius * 0.8,
],
},
properties: {},
};
});
// tree20 只包含一个 Mesh,可直接取出几何体和材质。
gltfLoader.load(urlUtils.getAssetUrl('assets/models/tree/planar/tree20.glb'), (gltf) => {
const tree = gltf.scene.children[0];
// 几何体不会自动转轴,Y 轴朝上的模型先旋转为 Z 轴朝上。
tree.geometry.rotateX(Math.PI / 2);
const trees = engine.add(new GeoInstancedMesh(tree.geometry, tree.material));
trees.dataSource = GeoJSONDataSource.fromGeoJSON(features);
engine.requestRender();
});
用 GeoInstancedMesh 在北京奥林匹克森林公园南园批量种下 300 棵同一模型的树,所有实例共用一份几何体和材质。
预览