代码
// 全部业务数值为固定模拟值;城市坐标仅用于展示区域间的流向关系。
const hubs = [
{id: 'gz', role: '湾区北部集散中心', name: '广州', lng: 113.285, lat: 23.137},
{id: 'fs', role: '制造业供应枢纽', name: '佛山', lng: 113.128, lat: 23.024},
{id: 'dg', role: '电子制造集货中心', name: '东莞', lng: 113.755, lat: 23.026},
{id: 'sz', role: '东岸分拨中心', name: '深圳', lng: 114.063, lat: 22.55},
{id: 'zs', role: '西岸中转站', name: '中山', lng: 113.399, lat: 22.523},
{id: 'zh', role: '西岸南部配送中心', name: '珠海', lng: 113.571, lat: 22.278},
{id: 'jm', role: '西翼冷链产地仓', name: '江门', lng: 113.087, lat: 22.585},
{id: 'hz', role: '东翼产业供应站', name: '惠州', lng: 114.421, lat: 23.117},
{id: 'ns', role: '港口冷链口岸', name: '南沙', lng: 113.542, lat: 22.812},
];
const categories = [
{id: 'express', name: '城市快件', color: '#ffc85c', short: '快件'},
{id: 'cold', name: '生鲜冷链', color: '#5fe0ff', short: '冷链'},
{id: 'supply', name: '产业供应', color: '#ff8f7a', short: '供应'},
];
// 固定阈值便于跨时段比较;同城需求柱和光柱按枢纽吞吐统一着色。
const volumeBands = [
{id: 'low', min: 0, label: '< 1,500', color: '#3f6390', side: '#2f4d73'},
{id: 'medium', min: 1500, label: '1,500–2,999', color: '#5e88ba', side: '#476b96'},
{id: 'high', min: 3000, label: '3,000–3,999', color: '#93b9e2', side: '#6f95bf'},
{id: 'peak', min: 4000, label: '≥ 4,000', color: '#e3f0ff', side: '#b3cbe6'},
];
function volumeBand(value) {
return volumeBands.findLast((band) => value >= band.min) || volumeBands[0];
}
const links = [
['gz', 'sz', 'express', 980],
['gz', 'dg', 'express', 780],
['dg', 'sz', 'express', 820],
['sz', 'zh', 'express', 640],
['fs', 'gz', 'express', 530],
['zs', 'sz', 'express', 520],
['jm', 'ns', 'cold', 420],
['hz', 'dg', 'cold', 570],
['ns', 'sz', 'cold', 680],
['ns', 'gz', 'cold', 610],
['zs', 'zh', 'cold', 360],
['fs', 'zs', 'cold', 440],
['fs', 'dg', 'supply', 880],
['dg', 'zh', 'supply', 630],
['hz', 'sz', 'supply', 720],
['jm', 'fs', 'supply', 510],
['gz', 'ns', 'supply', 760],
['ns', 'zs', 'supply', 560],
].map(([from, to, category, base], index) => ({
id: `flow-${index}`,
from,
to,
category,
base,
index,
}));
function snapshot(period = 1, category = 'all') {
period = Number.isFinite(period) ? Math.max(0, Math.min(2, Math.round(period))) : 1;
if (!categories.some((item) => item.id === category)) category = 'all';
const factors = {express: [0.68, 1, 1.38], cold: [1.35, 1, 0.76], supply: [1.12, 1, 0.72]};
const routes = links
.filter((item) => category === 'all' || item.category === category)
.map((item) => ({
...item,
volume: Math.round(
item.base *
factors[item.category][period] *
(1 + Math.sin(item.index * 1.7 + period) * 0.12),
),
color: categories.find((group) => group.id === item.category).color,
}));
return {
period,
category,
routes,
hubs: hubs.map((hub) => ({
...hub,
volume: routes
.filter((route) => route.from === hub.id || route.to === hub.id)
.reduce((sum, route) => sum + route.volume, 0),
})),
};
}
// 枢纽详情:到达与发出、三时段吞吐、业务构成和主要线路,均由 snapshot 推导。
function hubDetail(hubId, period = 1, category = 'all') {
const state = snapshot(period, category);
const hub = state.hubs.find((item) => item.id === hubId);
if (!hub) return null;
const touching = state.routes.filter((route) => route.from === hubId || route.to === hubId);
const sum = (list) => list.reduce((total, route) => total + route.volume, 0);
const all = snapshot(period).routes.filter((route) => route.from === hubId || route.to === hubId);
return {
hub,
inbound: sum(touching.filter((route) => route.to === hubId)),
outbound: sum(touching.filter((route) => route.from === hubId)),
byPeriod: [0, 1, 2].map(
(value) => snapshot(value, category).hubs.find((item) => item.id === hubId).volume,
),
byCategory: categories.map((group) => ({
...group,
volume: sum(all.filter((route) => route.category === group.id)),
})),
topRoutes: [...touching].sort((a, b) => b.volume - a.volume).slice(0, 3),
};
}
function hexagon(lng, lat, radius) {
const ring = Array.from({length: 6}, (_, i) => [
lng + (Math.cos((i * Math.PI) / 3) * radius) / Math.cos((lat * Math.PI) / 180),
lat + Math.sin((i * Math.PI) / 3) * radius,
]);
return [...ring, ring[0].slice()];
}
const feature = (type, coordinates, properties = {}) => ({
type: 'Feature',
geometry: {type, coordinates},
properties,
});
const collection = (features) => ({type: 'FeatureCollection', features});
// 每城生成七个固定模拟订单网格,不使用随机值,筛选和回放可复现。
function demandCells(state) {
return state.hubs.flatMap((hub, index) =>
Array.from({length: 7}, (_, i) => {
const angle = (i * Math.PI) / 3 + 0.2;
const lng = hub.lng + (i ? Math.cos(angle) * 0.047 : 0);
const lat = hub.lat + (i ? Math.sin(angle) * 0.041 : 0);
const value = Math.round(hub.volume * (i ? 0.07 + 0.025 * Math.sin(i * 2 + index) : 0.22));
return {
id: `${hub.id}-${i}`,
hubId: hub.id,
lng,
lat,
value,
coordinates: hexagon(lng, lat, 0.017),
};
}),
);
}
// 对二次曲线采样,交给内置 TrackLine 绘制与播放;仅表示流向,不代表实际道路。
function routeCoordinates(route) {
const from = hubs.find((hub) => hub.id === route.from);
const to = hubs.find((hub) => hub.id === route.to);
const dx = to.lng - from.lng;
const dy = to.lat - from.lat;
const control = [(from.lng + to.lng) / 2 - dy * 0.22, (from.lat + to.lat) / 2 + dx * 0.22];
return Array.from({length: 49}, (_, index) => {
const t = index / 48;
const s = 1 - t;
return [
s * s * from.lng + 2 * s * t * control[0] + t * t * to.lng,
s * s * from.lat + 2 * s * t * control[1] + t * t * to.lat,
];
});
}
// 地图初始化:地图先显示,内置图层就绪后自行绘制。
const $ = (id) => document.getElementById(id);
const map = new BMap.Map('map', {enableAdaptiveMinZoom: false});
map.enableScrollWheelZoom(true);
map.addControl(new BMap.ScaleControl());
map.addControl(new BMap.ZoomControl());
map.setDisplayOptions({
poi: false,
poiText: false,
poiIcon: false,
// 天空与浅色陆地同色,倾斜视角下远处不露出网格。
skyColors: ['rgba(32, 54, 86, 0)', 'rgba(32, 54, 86, 1)'],
});
let state = snapshot();
let ready = false;
let disposed = false;
let resizeTimer;
let routes = [];
const reduceMotion = matchMedia('(prefers-reduced-motion: reduce)').matches;
const layers = {};
const labels = [];
const prisms = [];
// 标签显示「今日累计」:起始值为本时段吞吐 × 当日已过小时数(08/14/20 点),
// 每当线路光点到达终点,起终两端各累加一批货量。
const START_HOURS = [8, 14, 20];
const BATCHES_PER_HOUR = 12;
let totals = new Map();
let selected = null;
const narrow = matchMedia('(max-width: 720px)');
const resetTotals = () => {
totals = new Map(state.hubs.map((hub) => [hub.id, hub.volume * START_HOURS[state.period]]));
};
const p = (lng, lat) => new BMap.Point(lng, lat);
const format = (value) => value.toLocaleString('zh-CN');
function addLayer(name, layer) {
layers[name] = layer;
map.addLayer(layer);
return layer;
}
function clearRoutes() {
routes.forEach(({track, replay}) => {
track.removeEventListener('onstatuschange', replay);
track.stop();
map.removeLayer(track);
});
routes = [];
}
function renderRoutes() {
clearRoutes();
state.routes.forEach((route) => {
const dot =
'<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18">' +
'<circle cx="9" cy="9" r="8" fill="' +
route.color +
'" fill-opacity=".25"/>' +
'<circle cx="9" cy="9" r="4" fill="#fff" stroke="' +
route.color +
'" stroke-width="2"/></svg>';
const track = new BMap.TrackLine({
strokeColor: route.color,
strokeWeight: 2 + route.volume / 600,
passedColor: null,
upcomingColor: null,
duration: 7 + (route.index % 5),
speedMode: 0,
autoStart: !reduceMotion,
movePoint: {
type: 'marker',
url: 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(dot),
size: [18, 18],
},
});
const replay = (event) => {
if (event.value.statusName !== 'finish') return;
arrive(route);
// 在结束事件处理完成后重播,筛选或退出后的旧轨迹不再启动。
queueMicrotask(() => {
if (!disposed && routes.some((item) => item.track === track)) track.start();
});
};
track.addEventListener('onstatuschange', replay);
routes.push({track, replay});
track.setData(feature('LineString', routeCoordinates(route), {}));
map.addLayer(track);
});
}
function arrive(route) {
const batch = Math.max(1, Math.round(route.volume / BATCHES_PER_HOUR));
[route.from, route.to].forEach((id) => totals.set(id, (totals.get(id) || 0) + batch));
updateLabel(route.from);
updateLabel(route.to);
if (selected === route.from || selected === route.to) renderDetail();
}
function labelHtml(hub) {
const active = selected === hub.id ? ' active' : '';
return `<div class="hub-label${active}">${hub.name}<b>${format(totals.get(hub.id) || 0)}</b></div>`;
}
// 只改数值文本,避免频繁重建标签内容。
function updateLabel(id) {
const value = document.querySelector(`[data-hub="${id}"] b`);
if (value) value.textContent = format(totals.get(id) || 0);
}
function selectHub(id) {
selected = selected === id ? null : id;
renderLabels();
renderDetail();
if (!narrow.matches) return;
if (selected) centerInGap(selected);
else fit();
}
function closeDetail() {
selected = null;
renderLabels();
renderDetail();
if (narrow.matches) fit();
}
// 窄屏抽屉打开后,把选中枢纽移到面板与抽屉之间的可见区域,缩放不变。
// 先以枢纽为地图中心,再按「可见区域中点 - 视口中点」平移,不依赖可能滞后的像素换算。
function centerInGap(id) {
const hub = hubs.find((item) => item.id === id);
const top = document.querySelector('.panel').getBoundingClientRect().bottom;
const bottom = $('detail').getBoundingClientRect().top;
map.setCenter(p(hub.lng, hub.lat), {noAnimation: true});
map.panBy(0, (top + bottom) / 2 - $('map').clientHeight / 2, {noAnimation: true});
}
function renderLabels() {
labels.forEach(({label, id}) => {
const hub = state.hubs.find((item) => item.id === id);
label.setContent(`<div data-hub="${id}">${labelHtml(hub)}</div>`);
if (hub.volume > 0) label.show();
else label.hide();
});
}
function renderDetail() {
const panel = $('detail');
const detail = selected && hubDetail(selected, state.period, state.category);
panel.hidden = !detail;
if (!detail) return;
const {hub, inbound, outbound, byPeriod, byCategory, topRoutes} = detail;
const name = (id) => hubs.find((item) => item.id === id).name;
const max = Math.max(...byPeriod, 1);
const share = byCategory.reduce((sum, item) => sum + item.volume, 0) || 1;
const times = ['08:00', '14:00', '20:00'];
$('detail-body').innerHTML =
`<h2>${hub.name}<small>${hub.role}</small></h2>` +
`<p class="live"><span>今日累计</span><b>${format(totals.get(hub.id) || 0)}</b><em>单</em></p>` +
(hub.volume
? `<dl class="io"><div><dt>到达</dt><dd>${format(inbound)}</dd></div><div><dt>发出</dt><dd>${format(outbound)}</dd></div><div><dt>本时段</dt><dd>${format(hub.volume)}</dd></div></dl>` +
`<h3>三时段吞吐 · 单/时</h3><div class="bars">${byPeriod
.map(
(value, i) =>
`<span class="${i === state.period ? 'now' : ''}"><i style="height:${Math.round((value / max) * 100)}%"></i><b>${format(value)}</b>${times[i]}</span>`,
)
.join('')}</div>` +
`<h3>业务构成</h3><div class="share">${byCategory
.map((item) => `<i style="flex:${item.volume};background:${item.color}"></i>`)
.join('')}</div><ul class="legend-row">${byCategory
.map(
(item) =>
`<li><i style="background:${item.color}"></i>${item.short}<b>${Math.round((item.volume / share) * 100)}%</b></li>`,
)
.join('')}</ul>` +
`<h3>主要线路</h3><ol class="lines">${topRoutes
.map(
(route) =>
`<li><i style="background:${route.color}"></i>${name(route.from)} → ${name(route.to)}<b>${format(route.volume)}</b></li>`,
)
.join('')}</ol>`
: '<p class="empty">当前业务下没有经过该枢纽的线路</p>');
}
function setState(period = state.period, category = state.category) {
state = snapshot(period, category);
// 切换时段或业务后累计值从该时段起始值重新计。
resetTotals();
document.querySelectorAll('[data-period]').forEach((button) => {
const active = Number(button.dataset.period) === state.period;
button.classList.toggle('active', active);
button.setAttribute('aria-pressed', String(active));
});
document.querySelectorAll('[data-category]').forEach((button) => {
const active = button.dataset.category === state.category;
button.classList.toggle('active', active);
button.setAttribute('aria-pressed', String(active));
});
if (ready) render();
}
function onResize() {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(fit, 180);
}
function dispose() {
disposed = true;
clearTimeout(resizeTimer);
window.removeEventListener('resize', onResize);
map.removeEventListener('load', onMapLoad);
clearRoutes();
labels.forEach((item) => map.removeOverlay(item.label));
prisms.forEach((prism) => map.removeOverlay(prism));
Object.values(layers).forEach((layer) => map.removeLayer(layer));
map.destroy();
}
$('detail-close').onclick = closeDetail;
$('categories').onclick = (event) => {
const button = event.target.closest('[data-category]');
if (button) setState(state.period, button.dataset.category);
};
$('periods').onclick = (event) => {
const button = event.target.closest('[data-period]');
if (button) setState(Number(button.dataset.period));
};
$('volume-legend').innerHTML = volumeBands
.map((band) => `<span><i style="background:${band.color}"></i>${band.label}</span>`)
.join('');
categories.forEach((category) => {
document.querySelector(`[data-category="${category.id}"]`).innerHTML =
`<i aria-hidden="true" style="background:${category.color}"></i>${category.short}`;
});
window.addEventListener('resize', onResize);
window.addEventListener('pagehide', dispose, {once: true});
window.addEventListener('pageshow', (event) => {
if (event.persisted) location.reload();
});
function onMapLoad() {
map.removeEventListener('load', onMapLoad);
queueMicrotask(() => {
if (disposed) return;
map.setMapStyle({
styleJson: [
{featureType: 'land', elementType: 'geometry', stylers: {color: '#203656ff'}},
{
featureType: 'water',
elementType: 'geometry',
stylers: {color: '#152541ff', visibility: 'on'},
},
{featureType: 'green', elementType: 'geometry', stylers: {color: '#21395aff'}},
...['manmade', 'building'].map((featureType) => ({
featureType,
elementType: 'geometry',
stylers: {color: '#243b5cff'},
})),
{
featureType: 'road',
elementType: 'geometry.fill',
stylers: {color: '#2b4568ff', weight: 1},
},
{featureType: 'road', elementType: 'geometry.stroke', stylers: {color: '#203656ff'}},
...['highway', 'nationalway', 'provincialway', 'cityhighway'].flatMap((featureType) => [
{
featureType,
elementType: 'geometry.fill',
stylers: {color: '#36557dff', weight: 1, visibility: 'on'},
},
{featureType, elementType: 'geometry.stroke', stylers: {color: '#203656ff'}},
]),
{featureType: 'arterial', elementType: 'geometry.fill', stylers: {color: '#304c72ff'}},
{
featureType: 'arterial',
elementType: 'geometry.stroke',
stylers: {color: '#203656ff'},
},
{featureType: 'local', elementType: 'geometry.fill', stylers: {color: '#284163ff'}},
...['boundary', 'country', 'district'].map((featureType) => ({
featureType,
elementType: 'geometry',
stylers: {color: '#4a6990ff'},
})),
{featureType: 'railway', elementType: 'all', stylers: {visibility: 'off'}},
{featureType: 'all', elementType: 'labels', stylers: {visibility: 'off'}},
],
});
initializeLayers();
ready = true;
setState();
});
}
map.addEventListener('load', onMapLoad);
fit();
function initializeLayers() {
addLayer(
'heat',
new BMap.Heatmap({
size: 8500,
unit: 'm',
weightField: 'count',
max: 3300,
opacity: 0.16,
maxOpacity: 0.26,
// 深蓝底用同色系渐变,只作需求密度的微弱提示。
gradient: {
0: 'rgba(63,99,144,0)',
0.35: '#3f6390',
0.65: '#5e88ba',
1: '#93b9e2',
},
}),
);
addLayer(
'cells',
new BMap.FillLayer({
crs: 'BD09LL',
style: {
fillColor: ['get', 'color'],
fillOpacity: 0.12,
strokeColor: '#93b9e2',
strokeWeight: 1,
strokeOpacity: 0.3,
},
}),
);
addLayer(
'ground',
new BMap.LineLayer({
crs: 'BD09LL',
style: {
strokeColor: '#9fb8d6',
strokeWeight: 1,
strokeOpacity: 0.45,
strokeStyle: 'dashed',
dashArray: [3, 6],
},
}),
);
addLayer(
'halo',
new BMap.PointShapeLayer({
crs: 'BD09LL',
style: {shapeType: 0, size: 32, color: '#ffc85c', opacity: 0.14, strokeWeight: 0},
}),
);
hubs.forEach((hub) => {
const label = new BMap.Label('', {
position: p(hub.lng, hub.lat),
// 标签整体放在网点右上方,左下角箭头尖端落在网点上。
offset: new BMap.Size(-6, -38),
});
label.setStyle({border: '0', background: 'transparent', padding: '0'});
label.addEventListener('click', () => selectHub(hub.id));
map.addOverlay(label);
labels.push({label, id: hub.id});
});
}
function render() {
const cells = demandCells(state),
active = state.hubs.filter((hub) => hub.volume > 0);
const bands = new Map(state.hubs.map((hub) => [hub.id, volumeBand(hub.volume)]));
layers.heat.setData(
collection(
cells
.filter((cell) => cell.value > 0)
.map((cell) => feature('Point', [cell.lng, cell.lat], {count: cell.value})),
),
);
layers.cells.setData(
collection(
cells
.filter((cell) => cell.value > 0)
.map((cell) =>
feature('Polygon', [cell.coordinates], {color: bands.get(cell.hubId).color}),
),
),
);
const ground = [];
active.forEach((hub) => {
cells
.filter((cell) => cell.hubId === hub.id)
.forEach((cell) =>
ground.push(
feature(
'LineString',
[
[hub.lng, hub.lat],
[cell.lng, cell.lat],
],
{id: cell.id},
),
),
);
});
layers.ground.setData(collection(ground));
layers.halo.setData(
collection(active.map((hub) => feature('Point', [hub.lng, hub.lat], {id: hub.id}))),
);
// 初始化时直接传入高度与颜色,避免在覆盖物异步模块就绪前调用 setter。
prisms.forEach((prism) => map.removeOverlay(prism));
prisms.length = 0;
cells
.filter((cell) => cell.value > 0)
.forEach((cell) => {
const band = bands.get(cell.hubId);
const prism = new BMap.Prism(
cell.coordinates.map((coord) => p(...coord)),
Math.max(80, cell.value * 10),
{
topFillColor: band.color,
topFillOpacity: 0.95,
sideFillColor: band.side,
sideFillOpacity: 0.8,
enableClicking: false,
},
);
map.addOverlay(prism);
prisms.push(prism);
});
renderLabels();
renderDetail();
renderRoutes();
}
function fit() {
if (!map) return;
const stage = $('map'),
compact = stage.clientWidth <= 720;
const topSpace = compact ? document.querySelector('.panel').offsetHeight + 28 : 0;
const bottomSpace = compact ? 80 : 0;
const zoom =
10.5 +
Math.log2(
Math.min(
stage.clientWidth / (compact ? 1400 : 1182),
Math.max(180, stage.clientHeight - topSpace - bottomSpace) / 820,
),
);
map.checkResize();
map.centerAndZoom(p(113.67, 22.71), zoom, {noAnimation: true});
map.setTilt(52, {noAnimation: true});
map.setHeading(-12, {noAnimation: true});
if (compact) map.panBy(0, (topSpace - bottomSpace) / 2, {noAnimation: true});
// 窄屏抽屉打开时,视口变化后仍把选中枢纽放在可见区域。
if (compact && selected) centerInGap(selected);
}
预览