代码
import {
BaiduMapConfig,
BaiduVectorTileProvider,
Engine,
GeoJSONDataSource,
Heatmap,
} from '@baidumap/mapv-three';
const container = document.getElementById('map');
const center = [116.3968, 40.0344];
const aspect = container.clientWidth / container.clientHeight;
const range = Math.max(6_400, 5_950 / aspect);
BaiduMapConfig.ak = '您的密钥';
const provider = new BaiduVectorTileProvider({
displayOptions: {
building: false,
poi: false,
},
});
const engine = new Engine(container, {
map: {
projection: 'EPSG:3857',
center,
range,
pitch: 0,
heading: 0,
provider,
},
rendering: {
sky: null,
enableAnimationLoop: false,
},
});
function point(coordinates, properties = {}) {
return {
type: 'Feature',
geometry: {
type: 'Point',
coordinates,
},
properties,
};
}
function sampleCloud([x, y, count, spread, weight]) {
return Array.from({length: count}, (_, index) => {
// 固定角度与半径序列让同一批采样每次打开都保持一致。
const angle = index * 2.399963;
const radius = Math.sqrt((index + 0.5) / count) * spread;
return point([x + Math.cos(angle) * radius, y + Math.sin(angle) * radius * 0.8, 6], {
count: weight * (1 - (radius / spread) * 0.35),
});
});
}
// 奥森南北园及周边入口的模拟采样,数量与权重共同决定热度。
const hotspots = [
[116.3886, 40.0431, 76, 0.0018, 1.7],
[116.395, 40.045, 105, 0.0017, 2.5],
[116.4008, 40.0441, 68, 0.0015, 1.8],
[116.3917, 40.039, 77, 0.0018, 1.5],
[116.3985, 40.039, 101, 0.0022, 2.0],
[116.3858, 40.0351, 63, 0.0015, 1.7],
[116.392, 40.0347, 92, 0.0018, 2.3],
[116.3983, 40.0325, 128, 0.002, 2.8],
[116.4053, 40.0341, 87, 0.0021, 1.9],
[116.3942, 40.0293, 67, 0.0017, 1.8],
[116.4001, 40.0278, 105, 0.0024, 2.2],
[116.4063, 40.0286, 71, 0.0016, 1.6],
];
const source = GeoJSONDataSource.fromGeoJSON(hotspots.flatMap(sampleCloud));
source.defineAttribute('count');
const heat = engine.add(
new Heatmap({
radius: 104,
keepSize: true,
maxValue: 82,
gradient: {
0.18: '#4052c6',
0.38: '#168ddd',
0.55: '#18cbb1',
0.7: '#f4de49',
0.86: '#ff8c24',
1: '#ec3b47',
},
}),
);
heat.dataSource = source;
const radius = document.getElementById('radius');
radius.addEventListener('input', () => {
heat.radius = Number(radius.value);
document.getElementById('radius-value').textContent = radius.value + ' 像素';
engine.requestRender();
});
const zoom = document.getElementById('zoom');
zoom.addEventListener('click', () => {
const close = zoom.getAttribute('aria-pressed') === 'false';
engine.map.lookAt(center, {
range: close ? range * 0.53 : range,
pitch: 0,
});
zoom.setAttribute('aria-pressed', String(close));
zoom.textContent = close ? '返回全览' : '放大看热区';
});
用南北两个园区的模拟客流绘制二维热力图。启用 keepSize 固定单个采样核的像素半径,缩放时随着点密度改变,热区会聚合或拆分。
预览