代码
import {
BaiduMapConfig,
BaiduVectorTileProvider,
DynamicSky,
Engine,
GeoJSONDataSource,
Polygon,
} from '@baidumap/mapv-three';
const container = document.getElementById('map');
const center = [116.168592, 39.91818];
const view = {pitch: 46, heading: 32};
const range = (770 * 1.42) / Math.min(1.42, container.clientWidth / container.clientHeight);
BaiduMapConfig.ak = '您的密钥';
const provider = new BaiduVectorTileProvider({
displayOptions: {
building: false,
poi: false,
},
});
const engine = new Engine(container, {
map: {
projection: 'EPSG:3857',
center,
range,
...view,
provider,
},
rendering: {
sky: null,
enableAnimationLoop: false,
},
});
engine.add(new DynamicSky());
function polygon(coordinates, properties = {}) {
return {
type: 'Feature',
geometry: {
type: 'Polygon',
coordinates,
},
properties,
};
}
const footprints = [
polygon(
[
[
[116.166592, 39.91698],
[116.167792, 39.91698],
[116.167792, 39.91808],
[116.166592, 39.91808],
[116.166592, 39.91698],
],
],
{
height: 45,
color: '#a9615c',
roof: '#e9a788',
},
),
polygon(
[
[
[116.168142, 39.91788],
[116.169292, 39.91788],
[116.169292, 39.91918],
[116.168892, 39.91918],
[116.168892, 39.91888],
[116.168142, 39.91888],
[116.168142, 39.91788],
],
],
{
height: 126,
color: '#5874ae',
roof: '#9cb9fb',
},
),
polygon(
[
[
[116.169542, 39.91733],
[116.170592, 39.91733],
[116.170592, 39.91853],
[116.169542, 39.91853],
[116.169542, 39.91733],
],
],
{
height: 83,
color: '#53988f',
roof: '#9ed8c3',
},
),
];
const buildings = GeoJSONDataSource.fromGeoJSON(footprints);
buildings.defineAttribute('height').defineAttribute('color');
const blocks = engine.add(
new Polygon({
extrude: true,
vertexHeights: true,
vertexColors: true,
}),
);
blocks.dataSource = buildings;
// 单独着色的屋顶位于各建筑的拉伸高度上方,可区分顶面与侧面。
const roofData = GeoJSONDataSource.fromGeoJSON(
footprints.map((feature) => {
const {height, roof} = feature.properties;
const rings = feature.geometry.coordinates.map((ring) =>
ring.map(([x, y]) => [x, y, height + 0.25]),
);
return polygon(rings, {
color: roof,
});
}),
);
roofData.defineAttribute('color');
const roofs = engine.add(
new Polygon({
vertexColors: true,
}),
);
roofs.dataSource = roofData;
const toggle = document.getElementById('extrude');
toggle.addEventListener('click', () => {
const extruded = !blocks.extrude;
blocks.extrude = extruded;
roofs.visible = extruded;
engine.map.lookAt(center, {
range,
...(extruded ? view : {pitch: 0, heading: 0}),
});
toggle.setAttribute('aria-pressed', String(extruded));
toggle.textContent = extruded ? '查看平面轮廓' : '恢复建筑高度';
engine.requestRender();
});
用 Polygon 的 extrude 与 vertexHeights 将示意建筑轮廓拉伸到不同高度,切换为平面轮廓可对照底面。 使用北京首钢园的百度矢量地图,覆盖物数据用于演示。
预览