Commit a553b63b by limin

refactor: 地图插件化,默认百度 JSAPI 4.0,高德预留

1 parent 9ebc8a7f
Showing 39 changed files with 1243 additions and 82 deletions
...@@ -11,6 +11,22 @@ ...@@ -11,6 +11,22 @@
VITE_AMAP_KEY= VITE_AMAP_KEY=
VITE_AMAP_SECURITY_CODE= VITE_AMAP_SECURITY_CODE=
# ============================================================================
# 地图厂商选择(默认 baidu)
# ----------------------------------------------------------------------------
# 只加载被选中厂商的 SDK,不请求另一家服务、不渲染另一家底图。
# 高德代码保留在仓库里,VITE_MAP_PROVIDER=amap 时切换;默认不构建、不加载。
# ============================================================================
VITE_MAP_PROVIDER=baidu
# 百度地图 JSAPI 4.0 凭证(浏览器端 AK)
# ----------------------------------------------------------------------------
# 1. 到百度地图开放平台申请「浏览器端」类型 AK,勾选 JSAPI WebGL 服务
# 2. Referer 白名单绑定实际访问域名(本地开发填 localhost / 127.0.0.1)
# 3. 全局坐标系在 load.ts 里声明为 GCJ-02,业务数据无需转 BD-09
# ============================================================================
VITE_BAIDU_KEY=
# 高德加载失败时的兜底排查提示开关(true 时控制台输出详细诊断信息) # 高德加载失败时的兜底排查提示开关(true 时控制台输出详细诊断信息)
VITE_AMAP_DEBUG=true VITE_AMAP_DEBUG=true
......
...@@ -12,3 +12,7 @@ VITE_AMAP_KEY=11b1dc16a79ade95fa0ef28246f4d518 ...@@ -12,3 +12,7 @@ VITE_AMAP_KEY=11b1dc16a79ade95fa0ef28246f4d518
VITE_AMAP_SECURITY_CODE=fc17677e508becf6ceb8aad81d442015 VITE_AMAP_SECURITY_CODE=fc17677e508becf6ceb8aad81d442015
# 生产关掉诊断输出,避免把加载失败细节铺到访客控制台 # 生产关掉诊断输出,避免把加载失败细节铺到访客控制台
VITE_AMAP_DEBUG=false VITE_AMAP_DEBUG=false
# 默认厂商:百度。浏览器端 AK,必须在百度控制台开通 JSAPI WebGL 服务并绑定域名白名单。
VITE_MAP_PROVIDER=baidu
VITE_BAIDU_KEY=OIwlROjnJyHgfHVfHJFS9XFrD24JIYHq
node_modules/ node_modules/
dist/ dist/
dist-*/
dist-ssr/ dist-ssr/
*.log *.log
......
/**
* 百度逆地理编码客户端(Web 服务 API v3)。
*
* 与主 client.ts(高德)并列存在:默认入口 key.ts / desktop-worker.ts 走百度,
* 高德客户端保留备查 —— 用户只有百度商授,不调高德服务。
*
* 坐标口径:数据全是 GCJ-02,百度 API 的 coordtype=gcj02ll 直接接受 GCJ-02,
* 不需要转 BD-09(见 packages/clean-core/src/geo/coord.ts)。
*
* 返回字段映射到与高德侧相同的 ResultFields,下游 fill.ts / 缓存格式一行不改。
*/
import type { LookupClient, ResultFields, RoadCandidate, Clock, StopHandle, Transport } from './client.ts';
import {
isRecord, text, distanceText, RateLimiter, RequestCancelled,
QueryError, StopRun, HttpFailure, StopSignal,
} from './client.ts';
import { UserError } from './errors.ts';
export const BAIDU_ENDPOINT = 'https://api.map.baidu.com/reverse_geocoding/v3/';
/** 状态码:百度用 status=0 表示成功;非 0 见 lbsyun 附录 */
const STATUS_OK = 0;
/** 需要停止整个运行的权限/配额类错误 */
const STOP_CODES = new Set([1, 2, 3, 4, 5, 101, 200, 201, 202, 203, 210, 211, 220, 230, 240, 250, 251, 252, 260, 261, 301, 302, 401, 402]);
/** 可重试的服务繁忙/并发超限 */
const RETRY_CODES = new Set([8, 9]);
const RETRYABLE_HTTP = new Set([408, 429, 500, 502, 503, 504]);
const REQUEST_TIMEOUT_SECONDS = 20;
const ATTEMPTS = 4;
class InvalidResponse extends Error {
name = 'InvalidResponse';
}
/** 把百度 result 映射成下游既有契约 */
export function extractBaiduFields(result: unknown): ResultFields {
const source = isRecord(result) ? result : {};
const ac = isRecord(source.addressComponent) ? source.addressComponent : {};
const roads = Array.isArray(source.roads) ? source.roads : [];
const candidates: RoadCandidate[] = [];
for (const road of roads) {
if (!isRecord(road)) continue;
const name = text(road.name);
const distance = distanceText(road.distance);
if (name !== '') candidates.push({ name, distance });
}
let nearest: RoadCandidate | null = null;
for (const c of candidates) {
if (c.distance === '') continue;
if (nearest === null || Number(c.distance) < Number(nearest.distance)) nearest = c;
}
const streetName = text(ac.street);
const streetNumber = text(ac.street_number);
const streetRoad = streetNumber !== '' ? streetNumber : streetName;
const streetDistance = distanceText(ac.distance);
return {
district: text(ac.district),
township: text(ac.town),
road: nearest !== null ? nearest.name : streetRoad,
road_source: nearest !== null ? 'nearest_road' : streetRoad !== '' ? 'street_number' : '',
road_distance: nearest !== null ? nearest.distance : streetDistance,
candidates,
street_road: streetRoad,
street_distance: streetDistance,
};
}
const fetchTransport: Transport = async (url, timeoutSeconds) => {
const response = await fetch(url, {
headers: { 'User-Agent': 'heatmap-plus-baidu-fill/1.0' },
signal: AbortSignal.timeout(timeoutSeconds * 1000),
});
if (!response.ok) throw new HttpFailure(response.status);
return { body: await response.text() };
};
export class BaiduClient implements LookupClient {
readonly key: string;
readonly stopEvent: StopHandle;
requests = 0;
private readonly limiter: RateLimiter;
private readonly transport: Transport;
constructor(
key: unknown,
qps = 100,
options: { transport?: Transport; clock?: Clock } = {},
) {
if (typeof key !== 'string' || key.trim() === '') {
throw new UserError('请设置 BAIDU_KEY 或在提示中输入百度服务端 AK');
}
this.key = key.trim();
// 复用 client.ts 的 StopSignal:可中断退避/限速语义与高德侧完全一致
this.stopEvent = new StopSignal(options.clock);
this.limiter = new RateLimiter(qps, this.stopEvent, options.clock);
this.transport = options.transport ?? fetchTransport;
}
async lookup(lng: string, lat: string): Promise<ResultFields> {
const params = new URLSearchParams({
ak: this.key,
output: 'json',
coordtype: 'gcj02ll',
extensions_road: 'true',
location: `${lat},${lng}`, // 百度顺序是 lat,lng —— 与高德相反
});
const url = `${BAIDU_ENDPOINT}?${params}`;
for (let attempt = 0; attempt < ATTEMPTS; attempt += 1) {
await this.limiter.acquire();
this.requests += 1;
let error = '';
try {
const { body } = await this.transport(url, REQUEST_TIMEOUT_SECONDS);
const payload: unknown = JSON.parse(body);
if (!isRecord(payload)) throw new InvalidResponse();
const status = Number(payload.status);
if (status === STATUS_OK) {
const result = payload.result;
if (!isRecord(result)) throw new InvalidResponse();
return extractBaiduFields(result);
}
if (STOP_CODES.has(status)) throw new StopRun(`百度服务/权限错误:${status}`);
if (!RETRY_CODES.has(status)) throw new QueryError(`百度请求失败:${status}`);
error = `百度服务繁忙:${status}`;
} catch (exc) {
if (exc instanceof StopRun || exc instanceof QueryError || exc instanceof RequestCancelled) throw exc;
if (exc instanceof HttpFailure) {
if (exc.code === 401 || exc.code === 403) throw new StopRun(`HTTP 权限错误:${exc.code}`);
if (!RETRYABLE_HTTP.has(exc.code)) throw new QueryError(`HTTP 请求失败:${exc.code}`);
error = `HTTP 暂时失败:${exc.code}`;
} else if (exc instanceof SyntaxError || exc instanceof InvalidResponse) {
error = '接口响应不是有效 JSON 或缺少结果对象';
} else {
error = '网络连接失败或超时';
}
}
if (attempt === ATTEMPTS - 1) throw new QueryError(`${error};已重试 ${ATTEMPTS - 1} 次`);
if (await this.stopEvent.wait(2 ** attempt)) throw new RequestCancelled('运行已停止');
}
throw new Error('unreachable');
}
}
...@@ -6,7 +6,8 @@ ...@@ -6,7 +6,8 @@
* Key 只走 workerData 或一次消息,不进环境变量、不进配置、不进日志。 * Key 只走 workerData 或一次消息,不进环境变量、不进配置、不进日志。
*/ */
import { runJob, type Report, type Stage } from './fill.ts'; import { runJob, type Report, type Stage } from './fill.ts';
import { AmapClient } from './client.ts'; import { BaiduClient } from './baidu-client.ts';
import type { LookupClient } from './client.ts';
import { UserError } from './errors.ts'; import { UserError } from './errors.ts';
import type { Job } from './desktop-core.ts'; import type { Job } from './desktop-core.ts';
import { parentPort, workerData } from 'node:worker_threads'; import { parentPort, workerData } from 'node:worker_threads';
...@@ -41,9 +42,9 @@ port.on('message', (message: WorkerIn) => { ...@@ -41,9 +42,9 @@ port.on('message', (message: WorkerIn) => {
}); });
/** 界面上没填 Key 时才问一次:问到之后只活在这一次运行里。 */ /** 界面上没填 Key 时才问一次:问到之后只活在这一次运行里。 */
async function client(qps: number): Promise<AmapClient> { async function client(qps: number): Promise<LookupClient> {
const trimmed = job.key.trim(); const trimmed = job.key.trim();
if (trimmed !== '') return new AmapClient(trimmed, qps); if (trimmed !== '') return new BaiduClient(trimmed, qps);
const given = await new Promise<string>((resolve) => { const given = await new Promise<string>((resolve) => {
resolver = resolve; resolver = resolve;
waitingFor = 'key'; waitingFor = 'key';
...@@ -53,10 +54,10 @@ async function client(qps: number): Promise<AmapClient> { ...@@ -53,10 +54,10 @@ async function client(qps: number): Promise<AmapClient> {
if (given.trim() === '') { if (given.trim() === '') {
// 没 Key 时 runJob 会在这里中止,什么文件都还没写 —— 别让人以为表格已经出来了 // 没 Key 时 runJob 会在这里中止,什么文件都还没写 —— 别让人以为表格已经出来了
throw new UserError(controller.signal.aborted throw new UserError(controller.signal.aborted
? '已按你的意思停下:还没有填高德 Key,接口一次都没问,本次没有写出文件' ? '已按你的意思停下:还没有填百度 AK,接口一次都没问,本次没有写出文件'
: '界面上没填高德 Key,接口问不了,本次没有写出文件;填上 Key 再点一次开始,已查过的坐标不会再花钱'); : '界面上没填百度 AK,接口问不了,本次没有写出文件;填上 Key 再点一次开始,已查过的坐标不会再花钱');
} }
return new AmapClient(given, qps); return new BaiduClient(given, qps);
} }
try { try {
......
/** 高德 Key 的取用:环境变量优先,其次终端隐藏输入。Key 不落盘、不进日志与缓存。 */ /** 百度 AK 的取用:环境变量优先,其次终端隐藏输入。AK 不落盘、不进日志与缓存。 */
import process from 'node:process'; import process from 'node:process';
import { AmapClient } from './client.ts'; import { BaiduClient } from './baidu-client.ts';
import type { LookupClient } from './client.ts';
import { UserError } from './errors.ts'; import { UserError } from './errors.ts';
/** 隐藏输入(等价 Python getpass):不回显,支持退格与 Ctrl+C。 */ /** 隐藏输入(等价 Python getpass):不回显,支持退格与 Ctrl+C。 */
export function promptHidden(question: string): Promise<string> { export function promptHidden(question: string): Promise<string> {
const input = process.stdin; const input = process.stdin;
if (input.isTTY !== true || input.setRawMode === undefined) { if (input.isTTY !== true || input.setRawMode === undefined) {
return Promise.reject(new UserError('当前终端不支持隐藏输入,请设置环境变量 AMAP_KEY')); return Promise.reject(new UserError('当前终端不支持隐藏输入,请设置环境变量 BAIDU_KEY'));
} }
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let value = ''; let value = '';
...@@ -47,10 +48,10 @@ export function promptHidden(question: string): Promise<string> { ...@@ -47,10 +48,10 @@ export function promptHidden(question: string): Promise<string> {
} }
/** 只有确有待查坐标时才会走到这里:能靠地址与缓存补齐的运行不需要 Key。 */ /** 只有确有待查坐标时才会走到这里:能靠地址与缓存补齐的运行不需要 Key。 */
export async function createClient(qps: number): Promise<AmapClient> { export async function createClient(qps: number): Promise<LookupClient> {
const fromEnv = typeof process.env.AMAP_KEY === 'string' ? process.env.AMAP_KEY.trim() : ''; const fromEnv = typeof process.env.BAIDU_KEY === 'string' ? process.env.BAIDU_KEY.trim() : '';
if (fromEnv !== '') return new AmapClient(fromEnv, qps); if (fromEnv !== '') return new BaiduClient(fromEnv, qps);
if (process.stdin.isTTY !== true) throw new UserError('非交互运行请先设置环境变量 AMAP_KEY'); if (process.stdin.isTTY !== true) throw new UserError('非交互运行请先设置环境变量 BAIDU_KEY');
const key = (await promptHidden('请输入高德 Web 服务 Key(隐藏输入):')).trim(); const key = (await promptHidden('请输入百度 Web 服务 AK(隐藏输入):')).trim();
return new AmapClient(key, qps); return new BaiduClient(key, qps);
} }
...@@ -96,7 +96,7 @@ describe('界面上的默认值', () => { ...@@ -96,7 +96,7 @@ describe('界面上的默认值', () => {
const file = path.join(root, 'ui-state.json'); const file = path.join(root, 'ui-state.json');
fs.writeFileSync(file, '{ 这不是 JSON', 'utf8'); fs.writeFileSync(file, '{ 这不是 JSON', 'utf8');
assert.deepEqual(loadState(file, base), base); assert.deepEqual(loadState(file, base), base);
fs.writeFileSync(file, JSON.stringify({ ...base, AMAP_KEY: 'DUMMY_NOT_A_REAL_KEY' }), 'utf8'); fs.writeFileSync(file, JSON.stringify({ ...base, BAIDU_KEY: 'DUMMY_NOT_A_REAL_KEY' }), 'utf8');
saveState(loadState(file, base), file); saveState(loadState(file, base), file);
assert.doesNotMatch(fs.readFileSync(file, 'utf8'), /DUMMY_NOT_A_REAL_KEY/); assert.doesNotMatch(fs.readFileSync(file, 'utf8'), /DUMMY_NOT_A_REAL_KEY/);
}); });
...@@ -431,7 +431,7 @@ describe('worker 真跑一遍', () => { ...@@ -431,7 +431,7 @@ describe('worker 真跑一遍', () => {
assert.ok(events.some((event) => event.type === 'key-needed'), '应当先问人要 Key'); assert.ok(events.some((event) => event.type === 'key-needed'), '应当先问人要 Key');
const failure = events.find((event): event is ErrorEvent => event.type === 'error'); const failure = events.find((event): event is ErrorEvent => event.type === 'error');
assert.ok(failure, '没有 Key 应当报一条看得懂的错误'); assert.ok(failure, '没有 Key 应当报一条看得懂的错误');
assert.match(failure.message, /没填高德 Key/); assert.match(failure.message, /没填百度 AK/);
assert.match(failure.message, /不会再花钱/); assert.match(failure.message, /不会再花钱/);
assert.match(failure.message, /没有写出文件/, '还没写文件,就不能说表格已经生成'); assert.match(failure.message, /没有写出文件/, '还没写文件,就不能说表格已经生成');
}); });
......
...@@ -5,12 +5,15 @@ interface Props { ...@@ -5,12 +5,15 @@ interface Props {
} }
/** /**
* 高德地图未就绪时的引导卡。 * 地图未就绪时的引导卡。
* *
* 两个高频阻塞场景都收敛到这里: * 两个高频阻塞场景都收敛到这里:
* - NO_KEY 未配置 Key,页面白屏前先给明确指引 * - NO_KEY 未配置 AK/Key,页面白屏前先给明确指引
* - LOAD_FAILED 脚本加载失败(无外网 / 域名白名单) * - LOAD_FAILED 脚本加载失败(无外网 / 域名白名单)
* 不打断式覆盖,用户按提示配好后热重载即可。 * 不打断式覆盖,用户按提示配好后热重载即可。
*
* Key 的变量名由当前 provider 决定(百度 VITE_BAIDU_KEY、高德 VITE_AMAP_KEY),
* 具体说明由 hint 给出 —— 本组件不认厂商。
*/ */
export function MapKeyGuide({ error }: Props) { export function MapKeyGuide({ error }: Props) {
if (!error) return null; if (!error) return null;
...@@ -24,7 +27,7 @@ export function MapKeyGuide({ error }: Props) { ...@@ -24,7 +27,7 @@ export function MapKeyGuide({ error }: Props) {
</div> </div>
<div className="hm-guide__text">{error.message}</div> <div className="hm-guide__text">{error.message}</div>
<div className="hm-guide__hint">{error.hint}</div> <div className="hm-guide__hint">{error.hint}</div>
<div className="hm-guide__code">{`# 配置高德 Key(Web端 JS API 类型,并绑定 localhost)\ncp .env.example .env.local\n# 在 .env.local 填入 VITE_AMAP_KEY 与 VITE_AMAP_SECURITY_CODE\npnpm dev`}</div> <div className="hm-guide__code">{`# 1. cp .env.example .env.local\n# 2. 填入当前厂商的 Key 变量名(见上方提示)\n# 3. 控制台确认服务已开通、域名白名单已绑定\npnpm dev`}</div>
</div> </div>
</div> </div>
); );
......
...@@ -29,8 +29,13 @@ import { rememberViewportAggregate } from './aggregate/viewSnapshot'; ...@@ -29,8 +29,13 @@ import { rememberViewportAggregate } from './aggregate/viewSnapshot';
import { ensureDetailLoaded } from './data/detailLoader'; import { ensureDetailLoaded } from './data/detailLoader';
import { IMPORT_PHASE_TEXT } from './data/importProgress'; import { IMPORT_PHASE_TEXT } from './data/importProgress';
import { districtShape } from './geo/districtShapes'; import { districtShape } from './geo/districtShapes';
import { AmapError, loadAmap, SHENZHEN_VIEW } from './map/loadAmap'; import {
import { HeatLayer } from './map/HeatLayer'; provider,
MapError,
type Basemap,
type HeatLayerLike,
} from './map/provider/registry';
import { SHENZHEN_VIEW } from './map/provider/shenzhenView';
/** /**
* 降噪开启时热力的整体不透明度上限。 * 降噪开启时热力的整体不透明度上限。
...@@ -304,7 +309,7 @@ function sameHeatKey(a: HeatKey | null, b: HeatKey): boolean { ...@@ -304,7 +309,7 @@ function sameHeatKey(a: HeatKey | null, b: HeatKey): boolean {
/** 把一帧的投影基准摆好。与各自绘层用的是同一个 Frame,口径不会分家 */ /** 把一帧的投影基准摆好。与各自绘层用的是同一个 Frame,口径不会分家 */
function projector( function projector(
frame: Frame, frame: Frame,
map: AMap.Map, map: Basemap,
zoom: number, zoom: number,
center: { getLng(): number; getLat(): number }, center: { getLng(): number; getLat(): number },
): Frame { ): Frame {
...@@ -421,7 +426,7 @@ function spotlightFrame(view: SpotlightView, result: SpotlightResult | null) { ...@@ -421,7 +426,7 @@ function spotlightFrame(view: SpotlightView, result: SpotlightResult | null) {
* 正常使用下只有用户点了谁才动一次,日志不会刷屏。 * 正常使用下只有用户点了谁才动一次,日志不会刷屏。
*/ */
function moveCamera( function moveCamera(
map: AMap.Map, map: Basemap,
reason: string, reason: string,
zoom: number, zoom: number,
center: [number, number], center: [number, number],
...@@ -484,8 +489,8 @@ export function MapStage() { ...@@ -484,8 +489,8 @@ export function MapStage() {
const containerRef = useRef<HTMLDivElement>(null); const containerRef = useRef<HTMLDivElement>(null);
const wrapRef = useRef<HTMLDivElement>(null); const wrapRef = useRef<HTMLDivElement>(null);
const mapRef = useRef<AMap.Map | null>(null); const mapRef = useRef<Basemap | null>(null);
const heatRef = useRef<HeatLayer | null>(null); const heatRef = useRef<HeatLayerLike | null>(null);
const clusterRef = useRef<ClusterLayer | null>(null); const clusterRef = useRef<ClusterLayer | null>(null);
const hotspotRef = useRef<HotspotLayer | null>(null); const hotspotRef = useRef<HotspotLayer | null>(null);
/** /**
...@@ -553,7 +558,7 @@ export function MapStage() { ...@@ -553,7 +558,7 @@ export function MapStage() {
* 当依赖,抽屉开合才触发 excludeUnderDrawer 那套补偿。 * 当依赖,抽屉开合才触发 excludeUnderDrawer 那套补偿。
*/ */
const rosterOpen = useHeatmapStore((s) => s.roster !== null); const rosterOpen = useHeatmapStore((s) => s.roster !== null);
const amapError = useHeatmapStore((s) => s.amapError); const mapError = useHeatmapStore((s) => s.mapError);
const analysisOn = useHeatmapStore((s) => s.analysisOn); const analysisOn = useHeatmapStore((s) => s.analysisOn);
const analysisParams = useHeatmapStore((s) => s.analysisParams); const analysisParams = useHeatmapStore((s) => s.analysisParams);
/** 手动重算序号:清单上那颗「重新计算」只负责 +1,取数仍由下面那个 effect 统一发起 */ /** 手动重算序号:清单上那颗「重新计算」只负责 +1,取数仍由下面那个 effect 统一发起 */
...@@ -593,7 +598,7 @@ export function MapStage() { ...@@ -593,7 +598,7 @@ export function MapStage() {
/** 黑点清单是否通栏停在左侧。同理,桶卡不许弹到它底下(判据与图例避让共用一份) */ /** 黑点清单是否通栏停在左侧。同理,桶卡不许弹到它底下(判据与图例避让共用一份) */
const dockOpen = useHeatmapStore(isDockOpen); const dockOpen = useHeatmapStore(isDockOpen);
const setAmapError = useHeatmapStore((s) => s.setAmapError); const setMapError = useHeatmapStore((s) => s.setMapError);
const select = useHeatmapStore((s) => s.select); const select = useHeatmapStore((s) => s.select);
// 读数块那两块入口(命中 / 点位)不在这里订阅了:它们连同读数一起搬进 // 读数块那两块入口(命中 / 点位)不在这里订阅了:它们连同读数一起搬进
// ToolbarReadouts(见文件末尾),为的是聚合回来时只重画那一小条 // ToolbarReadouts(见文件末尾),为的是聚合回来时只重画那一小条
...@@ -1699,23 +1704,20 @@ export function MapStage() { ...@@ -1699,23 +1704,20 @@ export function MapStage() {
(async () => { (async () => {
try { try {
const AMapCtor = await loadAmap();
if (disposed || !containerRef.current) return; if (disposed || !containerRef.current) return;
const map = new AMapCtor.Map(containerRef.current, { // 只创建被选中的那一家:alias 保证另一家连模块图都不在,
// 因此这里不会请求它的 SDK,也不会渲染它的底图。
const map = await provider.create(containerRef.current, {
zoom: SHENZHEN_VIEW.zoom, zoom: SHENZHEN_VIEW.zoom,
center: SHENZHEN_VIEW.center, center: SHENZHEN_VIEW.center,
viewMode: '2D', minZoom: GRID.minZoom,
resizeEnable: true, maxZoom: GRID.maxZoom,
rotateEnable: false, basemap: useHeatmapStore.getState().basemap,
pitchEnable: false,
zooms: [GRID.minZoom, GRID.maxZoom],
mapStyle: useHeatmapStore.getState().basemap,
showLabel: true,
}); });
mapRef.current = map; mapRef.current = map;
heatRef.current = new HeatLayer(map); heatRef.current = provider.createHeatLayer(map);
const cluster = new ClusterLayer(map); const cluster = new ClusterLayer(map);
cluster.setOptions({ showNumbers: useHeatmapStore.getState().showNumbers }); cluster.setOptions({ showNumbers: useHeatmapStore.getState().showNumbers });
clusterRef.current = cluster; clusterRef.current = cluster;
...@@ -1726,13 +1728,16 @@ export function MapStage() { ...@@ -1726,13 +1728,16 @@ export function MapStage() {
setMapReady(true); setMapReady(true);
} catch (err) { } catch (err) {
if (disposed) return; if (disposed) return;
if (err instanceof AmapError) { if (err instanceof MapError) {
setAmapError({ code: err.code, message: err.message, hint: err.hint }); setMapError({ code: err.code, message: err.message, hint: err.hint });
} else if (err instanceof Error && err.name === 'BaiduMapError') {
const e = err as unknown as { code: string; message: string; hint: string };
setMapError({ code: e.code, message: e.message, hint: e.hint });
} else { } else {
setAmapError({ setMapError({
code: 'LOAD_FAILED', code: 'LOAD_FAILED',
message: err instanceof Error ? err.message : String(err), message: err instanceof Error ? err.message : String(err),
hint: '查看浏览器控制台的高德错误码,确认 Key 类型、域名白名单与安全密钥配置。', hint: '查看浏览器控制台的错误码,确认 AK/Key 类型与域名白名单配置。',
}); });
} }
} }
...@@ -1756,8 +1761,8 @@ export function MapStage() { ...@@ -1756,8 +1761,8 @@ export function MapStage() {
hotspotRef.current = null; hotspotRef.current = null;
setMapReady(false); setMapReady(false);
}; };
// 只依赖 setAmapError:图层点击不再在初始化里回调,避免筛选/选中状态变化时重建地图 // 只依赖 setMapError:图层点击不再在初始化里回调,避免筛选/选中状态变化时重建地图
}, [setAmapError]); }, [setMapError]);
/* ---------------------- 点击路由:黑点优先于聚合桶 ---------------------- */ /* ---------------------- 点击路由:黑点优先于聚合桶 ---------------------- */
...@@ -2271,7 +2276,7 @@ export function MapStage() { ...@@ -2271,7 +2276,7 @@ export function MapStage() {
<StageProgress showFile={status === 'loading'} /> <StageProgress showFile={status === 'loading'} />
)} )}
{amapError && <MapKeyGuide error={amapError} />} {mapError && <MapKeyGuide error={mapError} />}
{status === 'error' && ( {status === 'error' && (
<div className="hm-map__overlay"> <div className="hm-map__overlay">
......
...@@ -110,7 +110,10 @@ function flush(frames = 3): void { ...@@ -110,7 +110,10 @@ function flush(frames = 3): void {
function makeCanvas(): DebugCanvas { function makeCanvas(): DebugCanvas {
const host = document.createElement('div'); const host = document.createElement('div');
document.body.appendChild(host); document.body.appendChild(host);
const dc = new DebugCanvas(fakeMap(), host); const dc = new DebugCanvas(
fakeMap() as unknown as import('../map/provider/types').Basemap,
host,
);
alive.push(dc); alive.push(dc);
dc.start(); dc.start();
return dc; return dc;
......
...@@ -14,6 +14,7 @@ import { APP_SCALE } from '../map/appOverlay'; ...@@ -14,6 +14,7 @@ import { APP_SCALE } from '../map/appOverlay';
import { mapGesture } from '../map/gesture'; import { mapGesture } from '../map/gesture';
import { GRID } from '../aggregate/grid'; import { GRID } from '../aggregate/grid';
import { debugVersion, getAggregateDebug, getDebugLayers, type AggregateDebug } from './debugBus'; import { debugVersion, getAggregateDebug, getDebugLayers, type AggregateDebug } from './debugBus';
import type { Basemap } from '../map/provider/types';
export interface DebugCanvasOptions { export interface DebugCanvasOptions {
/** 48px 聚合网格的经纬度分界线 */ /** 48px 聚合网格的经纬度分界线 */
...@@ -90,7 +91,7 @@ export class DebugCanvas { ...@@ -90,7 +91,7 @@ export class DebugCanvas {
private seenOptsKey = ''; private seenOptsKey = '';
constructor( constructor(
private readonly map: AMap.Map, private readonly map: Basemap,
host: HTMLElement, host: HTMLElement,
) { ) {
const canvas = document.createElement('canvas'); const canvas = document.createElement('canvas');
......
...@@ -24,6 +24,7 @@ import { ...@@ -24,6 +24,7 @@ import {
import { DebugCanvas, DEFAULT_DEBUG_OPTIONS, type DebugCanvasOptions } from './DebugCanvas'; import { DebugCanvas, DEFAULT_DEBUG_OPTIONS, type DebugCanvasOptions } from './DebugCanvas';
import { useHeatmapStore } from '@/store/useHeatmapStore'; import { useHeatmapStore } from '@/store/useHeatmapStore';
import './debug.css'; import './debug.css';
import type { Basemap } from '../map/provider/types';
/** 面板刷新的节奏(ms)。200ms 足够看清"什么时候出一帧",又不至于把注意力晃散。 */ /** 面板刷新的节奏(ms)。200ms 足够看清"什么时候出一帧",又不至于把注意力晃散。 */
const PANEL_REFRESH_MS = 200; const PANEL_REFRESH_MS = 200;
...@@ -78,7 +79,7 @@ function Row({ label, value }: { label: string; value: string }) { ...@@ -78,7 +79,7 @@ function Row({ label, value }: { label: string; value: string }) {
); );
} }
export function DebugHud({ map }: { map: AMap.Map | null }) { export function DebugHud({ map }: { map: Basemap | null }) {
const debugOn = useHeatmapStore((s) => s.debugOn); const debugOn = useHeatmapStore((s) => s.debugOn);
const toggleDebug = useHeatmapStore((s) => s.toggleDebug); const toggleDebug = useHeatmapStore((s) => s.toggleDebug);
......
...@@ -2,6 +2,7 @@ import { mercY, textWidth, type Overlay, type PaintEnv } from '@hm/map-overlay'; ...@@ -2,6 +2,7 @@ import { mercY, textWidth, type Overlay, type PaintEnv } from '@hm/map-overlay';
import { MAP_LABEL_FONT, PALETTE, paletteHexToRgb, rgbCss } from './palette'; import { MAP_LABEL_FONT, PALETTE, paletteHexToRgb, rgbCss } from './palette';
import { defineAppOverlay } from './appOverlay'; import { defineAppOverlay } from './appOverlay';
import { fmtDateTimeShort } from '@/utils/format'; import { fmtDateTimeShort } from '@/utils/format';
import type { Basemap } from './provider/types';
/** 主色与浅主色先折成 rgb 三元组:牌子描边每帧都要用,别在帧里反复解析 hex */ /** 主色与浅主色先折成 rgb 三元组:牌子描边每帧都要用,别在帧里反复解析 hex */
const PRIMARY = paletteHexToRgb(PALETTE.primary); const PRIMARY = paletteHexToRgb(PALETTE.primary);
...@@ -234,11 +235,12 @@ export class CasePinLayer { ...@@ -234,11 +235,12 @@ export class CasePinLayer {
/** 关闭按钮这一帧落在屏幕上的矩形(画布 CSS 像素)。null = 板上没有按钮或还没画 */ /** 关闭按钮这一帧落在屏幕上的矩形(画布 CSS 像素)。null = 板上没有按钮或还没画 */
private closeRect: { x: number; y: number; w: number; h: number } | null = null; private closeRect: { x: number; y: number; w: number; h: number } | null = null;
constructor(private readonly map: AMap.Map) {} constructor(private readonly map: Basemap) {}
private ensure() { private ensure() {
if (this.overlay) return; if (this.overlay) return;
this.overlay = defineAppOverlay(this.map, { this.overlay = defineAppOverlay(this.map, {
runtime: this.map.overlayRuntime,
id: 'casepin', id: 'casepin',
name: 'CasePinLayer · 定位标记层', name: 'CasePinLayer · 定位标记层',
// 高于黑点层(140):定位标记是用户此刻正在找的东西,盖过一切结论 // 高于黑点层(140):定位标记是用户此刻正在找的东西,盖过一切结论
......
...@@ -4,9 +4,10 @@ import { labelDomains } from '../aggregate/hotspotAnalysis'; ...@@ -4,9 +4,10 @@ import { labelDomains } from '../aggregate/hotspotAnalysis';
import type { HotspotRow } from '../aggregate/types'; import type { HotspotRow } from '../aggregate/types';
import { defineAppOverlay } from './appOverlay'; import { defineAppOverlay } from './appOverlay';
import { CLUSTER_LABEL, inkAt } from './palette'; import { CLUSTER_LABEL, inkAt } from './palette';
import { reference } from './HeatLayer'; import { reference } from './heatReference';
import { computeKeepMask, type SignificanceMask } from './significance'; import { computeKeepMask, type SignificanceMask } from './significance';
import type { HotspotGrid } from './HotspotLayer'; import type { HotspotGrid } from './HotspotLayer';
import type { Basemap } from './provider/types';
export type { SignificanceMask }; export type { SignificanceMask };
...@@ -167,7 +168,7 @@ export class ClusterLayer { ...@@ -167,7 +168,7 @@ export class ClusterLayer {
n: number; n: number;
} | null = null; } | null = null;
constructor(map: AMap.Map) { constructor(map: Basemap) {
this.buckets = createBucketsLayer(map, { this.buckets = createBucketsLayer(map, {
id: 'cluster', id: 'cluster',
name: 'ClusterLayer · 聚合数字层', name: 'ClusterLayer · 聚合数字层',
...@@ -177,6 +178,8 @@ export class ClusterLayer { ...@@ -177,6 +178,8 @@ export class ClusterLayer {
define: (m, spec) => define: (m, spec) =>
defineAppOverlay(m, { defineAppOverlay(m, {
...spec, ...spec,
// m 是内核给的 OverlayMap;运行时从外层 Basemap 带上,避免回退到全局 AMap
runtime: map.overlayRuntime,
extras: () => ({ extras: () => ({
built: this.buckets.overlay.mounted, built: this.buckets.overlay.mounted,
visible: this.visible, visible: this.visible,
......
...@@ -8,6 +8,7 @@ import { traceRoundedRings } from './roundedPath'; ...@@ -8,6 +8,7 @@ import { traceRoundedRings } from './roundedPath';
import { CLUSTER_LABEL, PALETTE, labelFont } from './palette'; import { CLUSTER_LABEL, PALETTE, labelFont } from './palette';
import { LABEL_MIN_R } from './ClusterLayer'; import { LABEL_MIN_R } from './ClusterLayer';
import { HOTSPOT_MAX_DRAW_PX, HOTSPOT_MIN_DRAW_PX } from './hotspotGeometry'; import { HOTSPOT_MAX_DRAW_PX, HOTSPOT_MIN_DRAW_PX } from './hotspotGeometry';
import type { Basemap } from './provider/types';
/** 黑点栅格几何(与 analyze / Worker 的 handleScope 同一口径) */ /** 黑点栅格几何(与 analyze / Worker 的 handleScope 同一口径) */
export interface HotspotGrid { export interface HotspotGrid {
...@@ -287,8 +288,9 @@ export class HotspotLayer { ...@@ -287,8 +288,9 @@ export class HotspotLayer {
/** 上一帧用的绘制上下文:命中判定(isPointInPath)要借它,没有 Path2D 的环境为 null */ /** 上一帧用的绘制上下文:命中判定(isPointInPath)要借它,没有 Path2D 的环境为 null */
private hitCtx: CanvasRenderingContext2D | null = null; private hitCtx: CanvasRenderingContext2D | null = null;
constructor(map: AMap.Map) { constructor(map: Basemap) {
this.overlay = defineAppOverlay(map, { this.overlay = defineAppOverlay(map, {
runtime: map.overlayRuntime,
id: 'hotspot', id: 'hotspot',
name: 'HotspotLayer · 黑点范围脚印层', name: 'HotspotLayer · 黑点范围脚印层',
// 高于聚合层(130):黑点是结论,压住数字是合理的层级关系 // 高于聚合层(130):黑点是结论,压住数字是合理的层级关系
......
...@@ -2,6 +2,7 @@ import { fitPlate, mercY, roundRectPath, textWidth, type Overlay, type PaintEnv ...@@ -2,6 +2,7 @@ import { fitPlate, mercY, roundRectPath, textWidth, type Overlay, type PaintEnv
import { MAP_LABEL_FONT, PALETTE, paletteHexToRgb, rgbCss } from './palette'; import { MAP_LABEL_FONT, PALETTE, paletteHexToRgb, rgbCss } from './palette';
import { defineAppOverlay } from './appOverlay'; import { defineAppOverlay } from './appOverlay';
import { fmtInt } from '@/utils/format'; import { fmtInt } from '@/utils/format';
import type { Basemap } from './provider/types';
/** /**
* 收窄标识层:把「屏上这会儿只画哪一片」写在地图上。 * 收窄标识层:把「屏上这会儿只画哪一片」写在地图上。
...@@ -117,11 +118,12 @@ export class ScopeLayer { ...@@ -117,11 +118,12 @@ export class ScopeLayer {
private layout: PlateLayout | null = null; private layout: PlateLayout | null = null;
private chips: ChipLayout[] = []; private chips: ChipLayout[] = [];
constructor(private readonly map: AMap.Map) {} constructor(private readonly map: Basemap) {}
private ensure() { private ensure() {
if (this.overlay) return; if (this.overlay) return;
this.overlay = defineAppOverlay(this.map, { this.overlay = defineAppOverlay(this.map, {
runtime: this.map.overlayRuntime,
id: 'scope', id: 'scope',
name: 'ScopeLayer · 收窄标识层', name: 'ScopeLayer · 收窄标识层',
// 高于黑点(140)、低于定位标记(150):它说的是「屏上这一片是哪一片」, // 高于黑点(140)、低于定位标记(150):它说的是「屏上这一片是哪一片」,
......
...@@ -21,6 +21,7 @@ import { ...@@ -21,6 +21,7 @@ import {
rgbCss, rgbCss,
} from './palette'; } from './palette';
import { corridorOf, hottestCell, type CorridorNode } from './spotlightGeometry'; import { corridorOf, hottestCell, type CorridorNode } from './spotlightGeometry';
import type { Basemap } from './provider/types';
/** /**
* 聚焦展示的形状种类,与 store 的 SpotlightKind 同一张名单。 * 聚焦展示的形状种类,与 store 的 SpotlightKind 同一张名单。
...@@ -329,8 +330,9 @@ export class SpotlightLayer { ...@@ -329,8 +330,9 @@ export class SpotlightLayer {
// map 只留给命中那一句反投影(containerToLngLat 是底图说了算的那一处,见 hitAt); // map 只留给命中那一句反投影(containerToLngLat 是底图说了算的那一处,见 hitAt);
// 出帧与画布都归 overlay,层里不再握着底图对象 // 出帧与画布都归 overlay,层里不再握着底图对象
constructor(private readonly map: AMap.Map) { constructor(private readonly map: Basemap) {
this.overlay = defineAppOverlay(map, { this.overlay = defineAppOverlay(map, {
runtime: map.overlayRuntime,
id: 'spotlight', id: 'spotlight',
name: 'SpotlightLayer · 聚焦形状层', name: 'SpotlightLayer · 聚焦形状层',
// 在黑点盘(140)之上、定位标记(150)之下:聚焦期间黑点盘本来就收起, // 在黑点盘(140)之上、定位标记(150)之下:聚焦期间黑点盘本来就收起,
......
...@@ -3,6 +3,7 @@ import { ...@@ -3,6 +3,7 @@ import {
type FrameScale, type FrameScale,
type Overlay, type Overlay,
type OverlayMap, type OverlayMap,
type OverlayRuntime,
type OverlaySpec, type OverlaySpec,
} from '@hm/map-overlay'; } from '@hm/map-overlay';
import { GRID } from '../aggregate/grid'; import { GRID } from '../aggregate/grid';
...@@ -58,13 +59,19 @@ export const APP_SCALE: FrameScale = { tileSize: GRID.tileSize, referenceLat: 22 ...@@ -58,13 +59,19 @@ export const APP_SCALE: FrameScale = { tileSize: GRID.tileSize, referenceLat: 22
export interface AppOverlaySpec extends Omit< export interface AppOverlaySpec extends Omit<
OverlaySpec, OverlaySpec,
'scale' | 'gesture' | 'shouldTime' | 'alwaysRender' | 'onMount' | 'onDestroy' 'scale' | 'gesture' | 'shouldTime' | 'alwaysRender' | 'runtime' | 'onMount' | 'onDestroy'
> { > {
/** /**
* 这一层才知道的那几项读数:有没有建、此刻可见吗、以及自己那句口径说明。 * 这一层才知道的那几项读数:有没有建、此刻可见吗、以及自己那句口径说明。
* 只在调试面板里出现,帧里没有它的事。 * 只在调试面板里出现,帧里没有它的事。
*/ */
extras?: () => Partial<LayerDebugStats> & { note?: string }; extras?: () => Partial<LayerDebugStats> & { note?: string };
/**
* 覆盖物运行时(高德=AMap.CustomLayer,百度=自管画布)。
* 由调用方从 Basemap.overlayRuntime 透传 —— 内核的 resolveRuntime 默认抓全局 AMap,
* 不传就会锁死高德,百度侧连层都建不起来。
*/
runtime?: OverlayRuntime;
} }
/** /**
...@@ -79,6 +86,8 @@ export function defineAppOverlay(map: OverlayMap, spec: AppOverlaySpec): Overlay ...@@ -79,6 +86,8 @@ export function defineAppOverlay(map: OverlayMap, spec: AppOverlaySpec): Overlay
return defineOverlay(map, { return defineOverlay(map, {
...rest, ...rest,
scale: APP_SCALE, scale: APP_SCALE,
// 厂商运行时必须透传:不传则内核回退到全局 AMap.CustomLayer(见 overlay.ts resolveRuntime)
...(spec.runtime ? { runtime: spec.runtime } : {}),
gesture: mapGesture, gesture: mapGesture,
shouldTime: debugEnabled, shouldTime: debugEnabled,
alwaysRender: LAYER_ALWAYS_RENDER, alwaysRender: LAYER_ALWAYS_RENDER,
......
...@@ -233,7 +233,7 @@ function spotlightData(cellCount: number): SpotlightData { ...@@ -233,7 +233,7 @@ function spotlightData(cellCount: number): SpotlightData {
describe('出帧预算 · 视图没变就不落笔', () => { describe('出帧预算 · 视图没变就不落笔', () => {
it('同一视图连开三帧,只有一帧真的清屏重画', () => { it('同一视图连开三帧,只有一帧真的清屏重画', () => {
const { map } = fakeMap(VIEW()); const { map } = fakeMap(VIEW());
const cluster = keep(new ClusterLayer(map)); const cluster = keep(new ClusterLayer(map as unknown as import("./provider/types").Basemap));
const b = buckets(); const b = buckets();
cluster.setData(b.lng, b.lat, b.count, b.gx, b.gy, 0.001, 0.001); cluster.setData(b.lng, b.lat, b.count, b.gx, b.gy, 0.001, 0.001);
const frame = frameOf(); const frame = frameOf();
...@@ -250,7 +250,7 @@ describe('出帧预算 · 视图没变就不落笔', () => { ...@@ -250,7 +250,7 @@ describe('出帧预算 · 视图没变就不落笔', () => {
it('视图每动一帧才清一帧屏', () => { it('视图每动一帧才清一帧屏', () => {
const view = VIEW(); const view = VIEW();
const { map } = fakeMap(view); const { map } = fakeMap(view);
const cluster = keep(new ClusterLayer(map)); const cluster = keep(new ClusterLayer(map as unknown as import("./provider/types").Basemap));
const b = buckets(); const b = buckets();
cluster.setData(b.lng, b.lat, b.count, b.gx, b.gy, 0.001, 0.001); cluster.setData(b.lng, b.lat, b.count, b.gx, b.gy, 0.001, 0.001);
const frame = frameOf(); const frame = frameOf();
...@@ -269,7 +269,7 @@ describe('出帧预算 · 不能落笔的层不接活', () => { ...@@ -269,7 +269,7 @@ describe('出帧预算 · 不能落笔的层不接活', () => {
it('方格数字层收起期间,改分母、让位表、点名都不画一笔', () => { it('方格数字层收起期间,改分母、让位表、点名都不画一笔', () => {
const view = VIEW(); const view = VIEW();
const { map } = fakeMap(view); const { map } = fakeMap(view);
const cluster = keep(new ClusterLayer(map)); const cluster = keep(new ClusterLayer(map as unknown as import("./provider/types").Basemap));
const b = buckets(); const b = buckets();
cluster.setData(b.lng, b.lat, b.count, b.gx, b.gy, 0.001, 0.001); cluster.setData(b.lng, b.lat, b.count, b.gx, b.gy, 0.001, 0.001);
cluster.setVisible(false); cluster.setVisible(false);
...@@ -296,7 +296,7 @@ describe('出帧预算 · 不能落笔的层不接活', () => { ...@@ -296,7 +296,7 @@ describe('出帧预算 · 不能落笔的层不接活', () => {
it('聚焦层收到空数据时不建画布;展开后清空那一屏只清一次', () => { it('聚焦层收到空数据时不建画布;展开后清空那一屏只清一次', () => {
const view = VIEW(); const view = VIEW();
const { map } = fakeMap(view); const { map } = fakeMap(view);
const spot = keep(new SpotlightLayer(map)); const spot = keep(new SpotlightLayer(map as unknown as import("./provider/types").Basemap));
spot.setData(null); spot.setData(null);
// 一屏不画的东西不该换来一张全屏 backing store(多数会话里这一层从来没出现过) // 一屏不画的东西不该换来一张全屏 backing store(多数会话里这一层从来没出现过)
expect(FakeCustomLayer.created.length).toBe(0); expect(FakeCustomLayer.created.length).toBe(0);
...@@ -321,7 +321,7 @@ describe('出帧预算 · 不能落笔的层不接活', () => { ...@@ -321,7 +321,7 @@ describe('出帧预算 · 不能落笔的层不接活', () => {
it('定位层:没有标记时连开帧都不必;标记挂着时视图没变的那些帧按 33 毫秒下限走', () => { it('定位层:没有标记时连开帧都不必;标记挂着时视图没变的那些帧按 33 毫秒下限走', () => {
const view = VIEW(); const view = VIEW();
const { map } = fakeMap(view); const { map } = fakeMap(view);
const pin = keep(new CasePinLayer(map)); const pin = keep(new CasePinLayer(map as unknown as import("./provider/types").Basemap));
pin.invalidate(); pin.invalidate();
expect(FakeCustomLayer.created.length).toBe(0); expect(FakeCustomLayer.created.length).toBe(0);
...@@ -350,7 +350,7 @@ describe('出帧预算 · 不能落笔的层不接活', () => { ...@@ -350,7 +350,7 @@ describe('出帧预算 · 不能落笔的层不接活', () => {
describe('出帧预算 · 量字只在第一次', () => { describe('出帧预算 · 量字只在第一次', () => {
it('同一视图里补画的帧一次字都不重量', () => { it('同一视图里补画的帧一次字都不重量', () => {
const { map } = fakeMap(VIEW()); const { map } = fakeMap(VIEW());
const hot = keep(new HotspotLayer(map)); const hot = keep(new HotspotLayer(map as unknown as import("./provider/types").Basemap));
hot.setData(hotspots()); hot.setData(hotspots());
const frame = frameOf(); const frame = frameOf();
frame(); frame();
...@@ -367,7 +367,7 @@ describe('出帧预算 · 量字只在第一次', () => { ...@@ -367,7 +367,7 @@ describe('出帧预算 · 量字只在第一次', () => {
it('缩放来回穿过同一档字号也不再重量(原先那张按缩放清空的宽度表就漏在这条上)', () => { it('缩放来回穿过同一档字号也不再重量(原先那张按缩放清空的宽度表就漏在这条上)', () => {
const view = VIEW(); const view = VIEW();
const { map } = fakeMap(view); const { map } = fakeMap(view);
const hot = keep(new HotspotLayer(map)); const hot = keep(new HotspotLayer(map as unknown as import("./provider/types").Basemap));
hot.setData(hotspots()); hot.setData(hotspots());
const frame = frameOf(); const frame = frameOf();
...@@ -390,7 +390,7 @@ describe('出帧预算 · 量字只在第一次', () => { ...@@ -390,7 +390,7 @@ describe('出帧预算 · 量字只在第一次', () => {
it('快拖那一拍整层不落笔也不量字;松手补的那一帧数字回来、仍然不重量', () => { it('快拖那一拍整层不落笔也不量字;松手补的那一帧数字回来、仍然不重量', () => {
const view = VIEW(); const view = VIEW();
const { map } = fakeMap(view); const { map } = fakeMap(view);
const hot = keep(new HotspotLayer(map)); const hot = keep(new HotspotLayer(map as unknown as import("./provider/types").Basemap));
hot.setData(hotspots()); hot.setData(hotspots());
const frame = frameOf(); const frame = frameOf();
frame(); frame();
...@@ -421,7 +421,7 @@ describe('出帧预算 · 量字只在第一次', () => { ...@@ -421,7 +421,7 @@ describe('出帧预算 · 量字只在第一次', () => {
it('方格的分格白线整档设一次参数,不逐格重复赋值', () => { it('方格的分格白线整档设一次参数,不逐格重复赋值', () => {
const view = VIEW(); const view = VIEW();
const { map } = fakeMap(view); const { map } = fakeMap(view);
const spot = keep(new SpotlightLayer(map)); const spot = keep(new SpotlightLayer(map as unknown as import("./provider/types").Basemap));
spot.setData(spotlightData(30)); spot.setData(spotlightData(30));
spot.setVisible(true); spot.setVisible(true);
const frame = frameOf(); const frame = frameOf();
......
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { HeatLayer } from './HeatLayer'; import { HeatLayer } from './provider/amap/HeatLayer';
/** /**
* 热力「喂数据」这一步的守卫(2026-10-15 性能调优时补)。 * 热力「喂数据」这一步的守卫(2026-10-15 性能调优时补)。
......
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { MAX_REF_PERCENTILE, reference } from './HeatLayer'; import { MAX_REF_PERCENTILE, reference } from './heatReference';
/** /**
* 归一化上限那条规则的守卫。 * 归一化上限那条规则的守卫。
......
/**
* 热力归一化上限算法 —— 与地图厂商无关,高德/百度两家共用。
*
* 从 provider/amap/HeatLayer.ts 抽出(2026-11-24):原文件带着这堆纯函数一起被
* ClusterLayer、store、两个测试引用;地图插件化后这些调用方不该因为换了厂商而失效。
*/
export interface HeatLayerStyle {
/** 热力扩散半径,像素 */
radius: number;
/** 热力不透明度上限(maxOpacity)。下限恒为 MIN_OPACITY */
opacity: number;
}
/**
* 默认值经过两次调整:
* - 26 → 40:半径越大色块越连贯,低密度区也能连成片而不是散点;
* - 40 → 52:热力层改为与聚合层共用网格后,权重点从「自适应细网格的几千个」
* 变成「48px 网格的几百个」,点间距变大,半径必须跟着放大才能连成片。
* ⚠️ 半径要略大于网格边长(48px),否则色块之间会出现空隙。
*/
export const DEFAULT_HEAT_STYLE: HeatLayerStyle = { radius: 52, opacity: 0.95 };
/** 不透明度下限:稀疏区留一层极淡底色,区分「有事但不多」与「完全没事」 */
export const HEAT_MIN_OPACITY = 0.06;
/** 分位基准:取 0.82,头部约 18% 的桶饱和,其余色阶拉开 */
export const MAX_REF_PERCENTILE = 0.82;
/** absMax / 分位 ≥ 这个倍数就视为长尾,一点都不补 */
const TIGHTNESS_FLOOR = 2;
function percentile(sorted: Int32Array, p: number): number {
const n = sorted.length;
if (n === 0) return 1;
const idx = Math.min(n - 1, Math.max(0, Math.round((n - 1) * p)));
return sorted[idx];
}
const HIST_SPARE = 4096;
let hist: Int32Array | null = null;
function percentileFast(weights: Int32Array, absMax: number, p: number): number {
const n = weights.length;
const idx = Math.min(n - 1, Math.max(0, Math.round((n - 1) * p)));
if (absMax + 1 > Math.max(HIST_SPARE, n * 4)) {
return percentile(Int32Array.from(weights).sort(), p);
}
if (!hist || hist.length <= absMax) hist = new Int32Array(absMax + 1);
hist.fill(0, 0, absMax + 1);
for (let i = 0; i < n; i += 1) hist[weights[i]] += 1;
let acc = 0;
for (let value = 0; value <= absMax; value += 1) {
acc += hist[value];
if (acc > idx) return value;
}
return absMax;
}
/**
* 归一化上限 = 分位基准 + 「按视野内分布紧凑度向实际峰值补一段」。
*
* 长尾(全市)s=0 → 纯分位,观感不变;紧凑(放大到黑点)s→1 → 抬到实际峰值,
* 把内部色阶拉开;独大(一个异常桶)s 也归 0,不被平均化成一片灰。
*/
export function reference(weights: Int32Array): number {
const n = weights.length;
if (n === 0) return 1;
let absMax = 0;
for (let i = 0; i < n; i += 1) {
const w = weights[i];
if (w > absMax) absMax = w;
}
const base = Math.max(percentileFast(weights, absMax, MAX_REF_PERCENTILE), 1);
const tightness = Math.min(1, Math.max(0, TIGHTNESS_FLOOR - absMax / base));
return Math.max(Math.round(base + (absMax - base) * tightness), 1);
}
...@@ -138,7 +138,7 @@ function squareDomain(): { mask: Uint8Array; row: HotspotRow } { ...@@ -138,7 +138,7 @@ function squareDomain(): { mask: Uint8Array; row: HotspotRow } {
describe('黑点图形 · 一片一条闭合轮廓', () => { describe('黑点图形 · 一片一条闭合轮廓', () => {
it('4×4 的域只产生 1 条闭合子路径,而不是 16 个格子的边', () => { it('4×4 的域只产生 1 条闭合子路径,而不是 16 个格子的边', () => {
const layer = new HotspotLayer(fakeMap()); const layer = new HotspotLayer(fakeMap() as unknown as import("./provider/types").Basemap);
const { mask, row } = squareDomain(); const { mask, row } = squareDomain();
layer.setData([row], GRID, mask); layer.setData([row], GRID, mask);
...@@ -165,7 +165,7 @@ describe('黑点图形 · 一片一条闭合轮廓', () => { ...@@ -165,7 +165,7 @@ describe('黑点图形 · 一片一条闭合轮廓', () => {
}); });
it('轮廓内的点能命中这一片,轮廓外的点不命中', () => { it('轮廓内的点能命中这一片,轮廓外的点不命中', () => {
const layer = new HotspotLayer(fakeMap()); const layer = new HotspotLayer(fakeMap() as unknown as import("./provider/types").Basemap);
const { mask, row } = squareDomain(); const { mask, row } = squareDomain();
layer.setData([row], GRID, mask); layer.setData([row], GRID, mask);
FakeCustomLayer.created[0]?.render?.(); FakeCustomLayer.created[0]?.render?.();
...@@ -178,7 +178,7 @@ describe('黑点图形 · 一片一条闭合轮廓', () => { ...@@ -178,7 +178,7 @@ describe('黑点图形 · 一片一条闭合轮廓', () => {
}); });
it('没拿到 grid+mask 时退回圆:走 arc,不画格子路径', () => { it('没拿到 grid+mask 时退回圆:走 arc,不画格子路径', () => {
const layer = new HotspotLayer(fakeMap()); const layer = new HotspotLayer(fakeMap() as unknown as import("./provider/types").Basemap);
const { row } = squareDomain(); const { row } = squareDomain();
layer.setData([row]); layer.setData([row]);
FakeCustomLayer.created[0]?.render?.(); FakeCustomLayer.created[0]?.render?.();
...@@ -216,7 +216,7 @@ describe('黑点图形 · 光效分档', () => { ...@@ -216,7 +216,7 @@ describe('黑点图形 · 光效分档', () => {
} }
it('大片走满配:三档光雾 + 暗底 + 主边 + 高光,且光雾只留在轮廓外', () => { it('大片走满配:三档光雾 + 暗底 + 主边 + 高光,且光雾只留在轮廓外', () => {
const layer = new HotspotLayer(fakeMap()); const layer = new HotspotLayer(fakeMap() as unknown as import("./provider/types").Basemap);
const { mask, row } = bigDomain(); const { mask, row } = bigDomain();
layer.setData([row], GRID, mask); layer.setData([row], GRID, mask);
FakeCustomLayer.created[0]?.render?.(); FakeCustomLayer.created[0]?.render?.();
...@@ -234,7 +234,7 @@ describe('黑点图形 · 光效分档', () => { ...@@ -234,7 +234,7 @@ describe('黑点图形 · 光效分档', () => {
}); });
it('选中只在本层加粗描边,不额外建画布、不起动画', () => { it('选中只在本层加粗描边,不额外建画布、不起动画', () => {
const layer = new HotspotLayer(fakeMap()); const layer = new HotspotLayer(fakeMap() as unknown as import("./provider/types").Basemap);
const { mask, row } = bigDomain(); const { mask, row } = bigDomain();
layer.setData([row], GRID, mask); layer.setData([row], GRID, mask);
FakeCustomLayer.created[0]?.render?.(); FakeCustomLayer.created[0]?.render?.();
......
/**
* 高德 provider。代码保留、默认不构建 —— 只有 VITE_MAP_PROVIDER=amap 时才被 registry 引入。
*
* 门面把 AMap.Map 收敛成 Basemap,业务层的 MapStage 只认接口。
* 旧实现里的 loadAmap / HeatLayer 原样迁移,行为不变。
*/
import type {
Basemap,
BasemapBounds,
CreateOptions,
HeatLayerLike,
LngLat,
MapProvider,
} from '../types';
import type { OverlayRuntime } from '@hm/map-overlay';
import { loadAmap, SHENZHEN_VIEW } from './load';
import { HeatLayer } from './HeatLayer';
import { BASEMAP_OPTIONS, DEFAULT_BASEMAP } from '../../palette';
export class AmapBasemap implements Basemap {
readonly raw: AMap.Map;
readonly overlayRuntime: OverlayRuntime;
constructor(
amap: typeof AMap,
map: AMap.Map,
) {
this.raw = map;
this.overlayRuntime = {
CustomLayer: amap.CustomLayer as unknown as OverlayRuntime['CustomLayer'],
};
}
getSize() {
return this.raw.getSize();
}
getCenter() {
const c = this.raw.getCenter();
return { getLng: () => c.getLng(), getLat: () => c.getLat() };
}
getZoom() {
return this.raw.getZoom();
}
lngLatToContainer(lnglat: LngLat) {
const p = this.raw.lngLatToContainer(lnglat);
return { x: p.x, y: p.y };
}
containerToLngLat(pixel: [number, number]) {
const ll = this.raw.containerToLngLat(pixel);
return { getLng: () => ll.getLng(), getLat: () => ll.getLat() };
}
getBounds(): BasemapBounds {
const b = this.raw.getBounds();
const sw = b.getSouthWest();
const ne = b.getNorthEast();
return {
getSouthWest: () => ({ getLng: () => sw.getLng(), getLat: () => sw.getLat() }),
getNorthEast: () => ({ getLng: () => ne.getLng(), getLat: () => ne.getLat() }),
};
}
setZoomAndCenter(
zoom: number,
center: LngLat,
immediately?: boolean,
duration?: number,
) {
this.raw.setZoomAndCenter(zoom, center, immediately, duration);
}
setMapStyle(style: string) {
this.raw.setMapStyle(style);
}
on(event: string, handler: (e: any) => void) {
this.raw.on(event, handler);
}
off(event: string, handler: (e: any) => void) {
this.raw.off(event, handler);
}
destroy() {
this.raw.destroy();
}
}
export const provider: MapProvider = {
name: '高德地图',
async create(container: HTMLElement, opts: CreateOptions): Promise<Basemap> {
const AMapCtor = await loadAmap();
const map = new AMapCtor.Map(container, {
zoom: opts.zoom,
center: opts.center,
viewMode: '2D',
resizeEnable: true,
rotateEnable: false,
pitchEnable: false,
zooms: [opts.minZoom, opts.maxZoom],
mapStyle: opts.basemap,
showLabel: true,
});
return new AmapBasemap(AMapCtor, map);
},
createHeatLayer(basemap: Basemap): HeatLayerLike {
return new HeatLayer((basemap as AmapBasemap).raw);
},
basemapStyles: BASEMAP_OPTIONS,
defaultBasemap: DEFAULT_BASEMAP,
};
export { SHENZHEN_VIEW };
/**
* 百度热力层 —— 内置 BMapGL.Heatmap,无 vendor、无外链库。
*
* 与高德侧共用同一套归一化口径(heatReference.reference:视野内 P82 + 紧凑度补偿),
* 所以切厂商后热力深浅、与聚合数字浓淡的对照关系都不变 —— 这是"保证当前功能"的关键。
*
* 数据格式:BMapGL.Heatmap.setData 吃 GeoJSON FeatureCollection,
* 权重取 properties[weightField](这里用 count),几何坐标按全局 GCJ-02 口径直接传入。
*/
import { Frame, mercY } from '@hm/map-overlay';
import { APP_SCALE } from '../../appOverlay';
import { HEAT_GRADIENT } from '../../palette';
import {
DEFAULT_HEAT_STYLE,
HEAT_MIN_OPACITY,
reference,
type HeatLayerStyle,
} from '../../heatReference';
import type { BaiduLayerLike } from './load';
import type { BaiduBasemap } from './basemap';
import type { HeatLayerLike } from '../types';
import { registerDebugLayer, unregisterDebugLayer } from '../../../debug/debugBus';
type HeatPoint = { lng: number; lat: number; count: number };
export class BaiduHeatLayer implements HeatLayerLike {
private heat: BaiduLayerLike | null = null;
private style: HeatLayerStyle = { ...DEFAULT_HEAT_STYLE };
private visible = true;
private data: HeatPoint[] = [];
private max = 1;
private lastMax = 0;
private feedKey = '';
private readonly frame = new Frame();
private inViewBuf = new Int32Array(0);
private allBuf = new Int32Array(0);
private readonly geo: { type: 'FeatureCollection'; features: unknown[] } = {
type: 'FeatureCollection',
features: [],
};
constructor(private readonly basemap: BaiduBasemap) {
registerDebugLayer({
id: 'heat',
name: 'BMapGL.Heatmap · 热力底色层',
zIndex: 110,
kind: 'webgl',
canvas: null,
read: () => ({
built: this.heat !== null,
visible: this.visible,
released: false,
cssW: 0,
cssH: 0,
dpr: 0,
total: this.count,
painted: this.heat && this.visible ? this.count : 0,
drawn: 0,
skipped: 0,
lastMs: 0,
light: false,
note: `归一化上限 ${Math.round(this.maxWeight)} · 半径 ${this.style.radius}px · 由百度 WebGL 逐帧重绘`,
}),
});
}
private ensure(): BaiduLayerLike {
if (!this.heat) {
const Ctor = this.basemap.gl.Heatmap;
if (!Ctor) {
throw new Error('当前百度 JSAPI 未提供内置 BMapGL.Heatmap(需 4.0)');
}
this.heat = new Ctor({
size: this.style.radius,
unit: 'px',
minOpacity: HEAT_MIN_OPACITY,
maxOpacity: this.style.opacity,
gradient: HEAT_GRADIENT,
maxZoom: 20,
zIndex: 110,
visible: this.visible,
weightField: 'count',
// referCenter 给深圳,规避大坐标 float32 抖动(官方强烈建议)
referCenter: { lng: 114.06, lat: 22.62 },
});
this.basemap.raw.addLayer(this.heat);
}
return this.heat;
}
setDataset(
lng: Int32Array,
lat: Int32Array,
count: Int32Array,
keep?: Uint8Array | null,
): void {
const heat = this.ensure();
const n = lng.length;
const size = this.basemap.getSize();
const center = this.basemap.getCenter();
this.frame.set(
this.basemap,
this.basemap.getZoom(),
center.getLng(),
center.getLat(),
APP_SCALE,
);
const key = `${n}:${lng.length}:${lat.length}:${count.length}:${keep ? 'k' : ''}`;
const sameSource = key === this.feedKey && this.data.length > 0;
const data: HeatPoint[] = sameSource ? this.data : [];
if (this.inViewBuf.length < n) {
this.inViewBuf = new Int32Array(n);
this.allBuf = new Int32Array(n);
}
const inView = this.inViewBuf;
const all = this.allBuf;
let v = 0;
let a = 0;
for (let i = 0; i < n; i += 1) {
if (keep && keep[i] !== 1) continue;
const lng6 = lng[i] / 1e6;
const lat6 = lat[i] / 1e6;
const c = count[i];
if (!sameSource) data.push({ lng: lng6, lat: lat6, count: c });
all[a++] = c;
const x = this.frame.x(lng6);
if (x < 0 || x > size.width) continue;
const y = this.frame.y(mercY(lat6));
if (y >= 0 && y <= size.height) inView[v++] = c;
}
this.feedKey = key;
this.data = data;
this.max = reference(v > 0 ? inView.subarray(0, v) : all.subarray(0, a));
// 数据与归一化上限都没变 → 只管显隐,不重传 GPU 数据
if (sameSource && this.lastMax === this.max) {
heat.setVisible?.(this.visible);
return;
}
this.lastMax = this.max;
this.geo.features = data.map((p) => ({
type: 'Feature',
geometry: { type: 'Point', coordinates: [p.lng, p.lat] },
properties: { count: p.count },
}));
heat.setData(this.geo);
heat.setOptions?.({
max: this.max,
size: this.style.radius,
minOpacity: HEAT_MIN_OPACITY,
maxOpacity: this.visible ? this.style.opacity : 0,
});
heat.setVisible?.(this.visible);
}
clear(): void {
this.data = [];
this.feedKey = '';
this.geo.features = [];
this.heat?.clearData?.();
}
setStyle(style: Partial<HeatLayerStyle>) {
this.style = { ...this.style, ...style };
this.heat?.setOptions?.({
size: this.style.radius,
maxOpacity: this.style.opacity,
});
}
setVisible(visible: boolean) {
this.visible = visible;
if (visible) this.ensure().setVisible?.(true);
else this.heat?.setVisible?.(false);
}
get count(): number {
return this.data.length;
}
get maxWeight(): number {
return this.lastMax;
}
destroy() {
unregisterDebugLayer('heat');
if (this.heat) {
this.basemap.raw.removeLayer(this.heat);
this.heat = null;
}
this.data = [];
this.geo.features = [];
}
}
/**
* 百度地图门面 + 自绘层运行时。
*
* 自绘层为什么不用百度原生 CustomLayer:
* 4.0 的 WebGLCustomLayer 只吃 GLSL,现有 Canvas2D 绘制逻辑(ctx.fillText / roundRectPath)
* 搬不过去;CustomHtmlLayer 是逐点 DOM,不适合一屏几百个桶。
* 所以沿用内核的 CanvasSurface 自管画布,但出帧方式改掉旧分支那套「裸 rAF 每帧强制重绘」:
*
* - 旧分支:setMap 时起一个常驻 rAF,每帧无条件调 render。静止时也在跑,且 rAF 与百度底图
* 的渲染时机不同步 → 拖动滞后半帧、落定错位,这就是当时「效果很差」的根因。
* - 这里:只在百度地图视图事件(moving/zooming/zoomend/moveend)到来看一帧,
* 用 rAF 合并同一帧内的多次事件;内核 CanvasSurface.begin 自己判「视图没变就跳过」,
* 静止时零绘制。视图采样在事件回调里读百度当前 center/zoom,与底图同拍。
*
* 4.0 全局坐标系已在 load.ts 里声明为 GCJ-02,本文件的坐标进出都按 GCJ-02,无需手动转换。
*/
import type { OverlayLayerLike, OverlayRuntime } from '@hm/map-overlay';
import type { Basemap, BasemapBounds, LngLat } from '../types';
import type { BaiduGLMap, BaiduGLNamespace, BaiduGLPixel, BaiduGLPoint } from './load';
/** 高德事件名 → 百度 4.0 事件名。取不到的原样透传 */
const EVENT_MAP: Record<string, string> = {
moveend: 'moveend',
zoomend: 'zoomend',
dragstart: 'dragstart',
zoomstart: 'zoomstart',
dragend: 'dragend',
mapmove: 'moving',
drag: 'moving',
zoomchange: 'zooming',
click: 'click',
};
/**
* 内核要的 CustomLayer 形状。canvas 由内核建好传进来,这里只负责挂到百度容器 +
* 在视图事件到时点名 render(真正画不画由内核 Surface 判定)。
*/
class BaiduCanvasLayer implements OverlayLayerLike {
render?: () => void;
private map: BaiduGLMap | null = null;
private raf = 0;
private readonly zIndex: number;
constructor(
private readonly canvas: HTMLCanvasElement,
opts: { zIndex: number; zooms: [number, number]; alwaysRender: boolean },
) {
this.zIndex = opts.zIndex;
}
/** 事件到 → 合并到下一帧点一次名。rAF 只在这里按需起,不是常驻 */
private readonly onViewChange = (): void => {
if (this.raf) return;
this.raf = requestAnimationFrame(() => {
this.raf = 0;
this.render?.();
});
};
private readonly VIEW_EVENTS = ['moving', 'zooming', 'moveend', 'zoomend', 'resize'];
setMap(target: unknown | null): void {
if (target) {
const map = target as BaiduGLMap;
this.map = map;
const container = map.getContainer();
const c = this.canvas;
c.style.position = 'absolute';
c.style.top = '0';
c.style.left = '0';
c.style.pointerEvents = 'none';
// 200 是瓦片之上的底线;各层 zIndex(热力110/聚合130/热点140)保持相对顺序
c.style.zIndex = String(200 + this.zIndex);
container.appendChild(c);
for (const event of this.VIEW_EVENTS) map.addEventListener(event, this.onViewChange);
// 挂载后点一帧:否则第一次数据到位前画布空白
this.onViewChange();
} else {
if (this.raf) cancelAnimationFrame(this.raf);
this.raf = 0;
if (this.map) {
for (const event of this.VIEW_EVENTS) {
this.map.removeEventListener(event, this.onViewChange);
}
}
this.canvas.remove();
this.map = null;
}
}
show(): void {
this.canvas.style.display = '';
}
hide(): void {
this.canvas.style.display = 'none';
}
}
export class BaiduBasemap implements Basemap {
readonly raw: BaiduGLMap;
/** BMapGL 命名空间;厂商内部的图层工厂从这里取构造器 */
readonly gl: BaiduGLNamespace;
readonly overlayRuntime: OverlayRuntime;
constructor(
private readonly B: BaiduGLNamespace,
map: BaiduGLMap,
) {
this.raw = map;
this.gl = B;
this.overlayRuntime = {
CustomLayer: BaiduCanvasLayer as unknown as OverlayRuntime['CustomLayer'],
};
}
getSize() {
const s = this.raw.getSize();
return { width: s.width, height: s.height };
}
getCenter() {
const p = this.raw.getCenter();
return { getLng: () => p.lng, getLat: () => p.lat };
}
getZoom() {
return this.raw.getZoom();
}
lngLatToContainer(lnglat: LngLat) {
const p: BaiduGLPixel = this.raw.pointToOverlayPixel(
new this.B.Point(lnglat[0], lnglat[1]) as BaiduGLPoint,
);
return { x: p.x, y: p.y };
}
containerToLngLat(pixel: [number, number]) {
const p: BaiduGLPoint = this.raw.overlayPixelToPoint(
new this.B.Pixel(pixel[0], pixel[1]) as BaiduGLPixel,
);
return { getLng: () => p.lng, getLat: () => p.lat };
}
getBounds(): BasemapBounds {
const b = this.raw.getBounds();
const sw = b.getSouthWest();
const ne = b.getNorthEast();
return {
getSouthWest: () => ({ getLng: () => sw.lng, getLat: () => sw.lat }),
getNorthEast: () => ({ getLng: () => ne.lng, getLat: () => ne.lat }),
};
}
setZoomAndCenter(
zoom: number,
center: LngLat,
immediately?: boolean,
_duration?: number,
) {
// 百度 4.0 没有 duration 参数;immediately 用 options 控制(这里按旧接口语义近似)
this.raw.setZoomAndCenter(zoom, new this.B.Point(center[0], center[1]) as BaiduGLPoint, immediately);
}
setMapStyle(style: string) {
// 高德 amap://styles/* → 百度 4.0 主题名
this.raw.setMapStyle({ style: mapBaiduStyle(style) });
}
on(event: string, handler: (e: any) => void) {
this.raw.addEventListener(EVENT_MAP[event] ?? event, handler as (e: unknown) => void);
}
off(event: string, handler: (e: any) => void) {
this.raw.removeEventListener(EVENT_MAP[event] ?? event, handler as (e: unknown) => void);
}
destroy() {
this.raw.destroy();
}
}
/** 高德风格 → 百度内置主题。对不上的落回 normal */
function mapBaiduStyle(style: string): string {
const s = style.toLowerCase();
if (s.includes('dark') || s.includes('night') || s.includes('black')) return 'midnight';
if (s.includes('grey') || s.includes('gray') || s.includes('light') || s.includes('fresh')) {
return 'grayscale';
}
if (s.includes('whitesmoke') || s.includes('blue')) return 'light';
return 'normal';
}
/**
* 百度 provider(默认)。
*
* 只加载百度 SDK、只渲染百度底图。高德目录不进 import 图(见 vite.config.ts 的 alias)。
*/
import type { Basemap, CreateOptions, HeatLayerLike, MapProvider } from '../types';
import { loadBaidu } from './load';
import { BaiduBasemap } from './basemap';
import { BaiduHeatLayer } from './HeatLayer';
/** 百度 4.0 内置主题名。对应高德那四档,观感尽量靠拢 */
export const BAIDU_BASEMAP_OPTIONS = [
{ label: '极简灰白', value: 'light' },
{ label: '标准', value: 'normal' },
{ label: '灰阶', value: 'grayscale' },
{ label: '深蓝夜', value: 'midnight' },
] as const;
export const BAIDU_DEFAULT_BASEMAP = BAIDU_BASEMAP_OPTIONS[0].value;
export const provider: MapProvider = {
name: '百度地图',
async create(container: HTMLElement, opts: CreateOptions): Promise<Basemap> {
const B = await loadBaidu();
const map = new B.Map(container, {
zoom: opts.zoom,
center: new B.Point(opts.center[0], opts.center[1]),
minZoom: opts.minZoom,
maxZoom: opts.maxZoom,
enableRotate: false,
enableTilt: false,
enableMapClick: false,
mapStyle: { style: opts.basemap === 'normal' ? 'normal' : opts.basemap },
});
// 4.0 的 center+zoom 需显式 centerAndZoom 才稳(构造参数只给初值)
map.centerAndZoom(new B.Point(opts.center[0], opts.center[1]), opts.zoom, {
noAnimation: true,
});
return new BaiduBasemap(B, map);
},
createHeatLayer(basemap: Basemap): HeatLayerLike {
return new BaiduHeatLayer(basemap as BaiduBasemap);
},
basemapStyles: BAIDU_BASEMAP_OPTIONS,
defaultBasemap: BAIDU_DEFAULT_BASEMAP,
};
/** SHENZHEN_VIEW 与厂商无关,仍从公共定义取(避免 MapStage 改两处) */
export const SHENZHEN_VIEW = {
center: [114.06, 22.62] as [number, number],
zoom: 11,
};
/**
* 百度 JSAPI 4.0 动态加载。
*
* 要点(2026-11-24 对着官方文档 + 实际拉取的 900KB 脚本核实过):
* 1) 4.0 的 script 入口仍是 `api?v=1.0&type=webgl&ak=...&callback=...`(文档原文如此,
* 不要自作聪明改成 v=4.0 — 那个 URL 只影响 CSS 版本,主脚本由 getscript 决定);
* 真正切到 4.0 是在 getscript 的 `v=4.0`,见下面 SRC 常量。
* 2) 全局命名空间实际是 `BMapGL`(4.0 脚本末尾 `(BMapGL,"BMapGL")`),文档里的 `BMap.*`
* 是兼容别名。这里统一用 BMapGL,避免与旧 2.0 文档混。
* 3) 坐标系:数据全是 GCJ-02(见 packages/clean-core/src/geo/coord.ts)。百度默认 BD-09,
* 不转就偏 10~50m。4.0 提供 BMapGL.coordType = BMAP_COORD_GCJ02 全局声明,
* 内部自动双向转换 —— 只在建图前设一次,业务层坐标口径完全不动。
* 4) AK 校验失败时脚本仍 200,靠 script.onerror 抓不到:必须有超时兜底 + callback 里检查。
*/
export type BaiduErrorCode = 'NO_KEY' | 'LOAD_FAILED';
export class BaiduMapError extends Error {
code: BaiduErrorCode;
hint: string;
constructor(code: BaiduErrorCode, message: string, hint: string) {
super(message);
this.name = 'BaiduMapError';
this.code = code;
this.hint = hint;
}
}
/** 全局 BMapGL 命名空间。只声明本项目用到的形状,不引第三方 d.ts */
export interface BaiduGLPoint {
lng: number;
lat: number;
}
export interface BaiduGLPixel {
x: number;
y: number;
}
export interface BaiduGLSize {
width: number;
height: number;
}
export interface BaiduGLBounds {
getSouthWest(): BaiduGLPoint;
getNorthEast(): BaiduGLPoint;
}
export interface BaiduGLNamespace {
Map: new (container: HTMLElement, opts?: Record<string, unknown>) => BaiduGLMap;
Point: new (lng: number, lat: number) => BaiduGLPoint;
Pixel: new (x: number, y: number) => BaiduGLPixel;
Heatmap?: new (opts: Record<string, unknown>) => BaiduLayerLike;
ClusterLayer?: new (opts: Record<string, unknown>) => BaiduLayerLike;
/** 全局坐标系声明用的是 BMAP_COORD_GCJ02(脚本内确认存在) */
coordType?: string;
[key: string]: unknown;
}
/** 可视化图层(Heatmap / ClusterLayer)的公共形状 */
export interface BaiduLayerLike {
setData(data: unknown): BaiduLayerLike;
clearData?(): BaiduLayerLike;
setVisible?(visible: boolean): void;
setOptions?(opts: Record<string, unknown>): BaiduLayerLike;
setZIndex?(z: number): void;
setRenderStage?(stage: string): void;
redraw?(): void;
addEventListener?(event: string, handler: (e: unknown) => void): void;
removeEventListener?(event: string, handler: (e: unknown) => void): void;
destroy?(): void;
}
export interface BaiduGLMap {
centerAndZoom(center: BaiduGLPoint, zoom: number, opts?: Record<string, unknown>): void;
getSize(): BaiduGLSize;
getCenter(): BaiduGLPoint;
getZoom(): number;
getBounds(): BaiduGLBounds;
setZoom(zoom: number): void;
setZoomAndCenter(zoom: number, point: BaiduGLPoint, immediately?: boolean): void;
setMapStyle(style: Record<string, unknown>): void;
getContainer(): HTMLElement;
pointToOverlayPixel(point: BaiduGLPoint): BaiduGLPixel;
overlayPixelToPoint(pixel: BaiduGLPixel): BaiduGLPoint;
addEventListener(event: string, handler: (e: unknown) => void): void;
removeEventListener(event: string, handler: (e: unknown) => void): void;
addLayer(layer: unknown): void;
removeLayer(layer: unknown): void;
destroy(): void;
}
interface BaiduWindow extends Window {
BMapGL?: BaiduGLNamespace;
BMAP_COORD_GCJ02?: string;
__onBaiduGLReady?: () => void;
}
const w = window as unknown as BaiduWindow;
export function getBaiduKey(): string {
return (import.meta.env.VITE_BAIDU_KEY ?? '').trim();
}
let loading: Promise<BaiduGLNamespace> | null = null;
/** 脚本地址:v=1.0&type=webgl 是官方 4.0 文档给的异步加载格式 */
const SCRIPT_SRC = (key: string, cb: string) =>
`https://api.map.baidu.com/api?v=1.0&type=webgl&ak=${encodeURIComponent(key)}&callback=${cb}`;
const CB_NAME = '__onBaiduGLReady';
const TIMEOUT_MS = 15000;
export function loadBaidu(): Promise<BaiduGLNamespace> {
if (loading) return loading;
loading = new Promise<BaiduGLNamespace>((resolve, reject) => {
const key = getBaiduKey();
if (!key) {
reject(
new BaiduMapError(
'NO_KEY',
'未配置百度地图 AK',
'在 .env.local 填入 VITE_BAIDU_KEY(浏览器端 AK),并确认控制台已勾选 JSAPI WebGL 服务。',
),
);
return;
}
if (w.BMapGL) {
declareGcj02(w.BMapGL);
resolve(w.BMapGL);
return;
}
let timer = 0;
const cleanup = () => {
window.clearTimeout(timer);
(window as unknown as Record<string, unknown>)[CB_NAME] = undefined;
};
(window as unknown as Record<string, unknown>)[CB_NAME] = (() => {
cleanup();
const B = w.BMapGL;
if (!B) {
reject(
new BaiduMapError(
'LOAD_FAILED',
'百度 JSAPI 回调已触发但未挂载 window.BMapGL',
'多半是 AK 类型不对或未开通 WebGL 服务,打开控制台看百度返回的错误码。',
),
);
return;
}
declareGcj02(B);
resolve(B);
}) as BaiduWindow['__onBaiduGLReady'];
timer = window.setTimeout(() => {
cleanup();
reject(
new BaiduMapError(
'LOAD_FAILED',
'百度 JSAPI 加载超时',
'检查网络是否可访问 api.map.baidu.com;企业内网需放行该域名。',
),
);
}, TIMEOUT_MS);
const script = document.createElement('script');
script.src = SCRIPT_SRC(key, CB_NAME);
script.async = true;
script.onerror = () => {
cleanup();
reject(
new BaiduMapError(
'LOAD_FAILED',
'百度 JSAPI 脚本加载失败',
'常见原因:无外网、企业网络拦截 api.map.baidu.com、或 AK 类型不匹配。',
),
);
};
document.head.appendChild(script);
});
return loading;
}
/**
* 声明全局 GCJ-02 坐标口径 —— 必须在 new Map 之前。
* BMAP_COORD_GCJ02 是百度脚本注入的全局常量(4.0 脚本里确认存在),
* 其值为 'gcj02',这里对常量缺失做兜底,避免脚本版本差异导致 undefined。
*/
function declareGcj02(B: BaiduGLNamespace): void {
const gcj = w.BMAP_COORD_GCJ02 ?? 'gcj02';
if (B.coordType !== gcj) B.coordType = gcj;
}
/**
* 地图厂商注册点。
*
* `@map-provider` 由 vite.config.ts 的 alias 指向 provider/baidu 或 provider/amap,
* 由 VITE_MAP_PROVIDER 决定(默认 baidu)。未选中的目录不进 import 图 —— Rollup 不会打包,
* 浏览器也不会请求它,自然不会加载另一家的 SDK、不会调另一家服务。
*
* 业务层只从本文件取 provider,不直接 import 任何厂商目录。
*/
import { provider } from '@map-provider';
export { provider };
/** 当前厂商可用的底图样式。FilterPanel 用它渲染选择器,store 用它取默认值 */
export const BASEMAP_OPTIONS = provider.basemapStyles;
export const DEFAULT_BASEMAP = provider.defaultBasemap;
export type {
Basemap,
BasemapBounds,
HeatLayerLike,
LngLat,
MapProvider,
} from './types';
export { MapError } from './types';
/** 深圳默认视野。与地图厂商无关,业务层和两家 provider 共用 */
export const SHENZHEN_VIEW = {
center: [114.06, 22.62] as [number, number],
zoom: 11,
};
/**
* 地图厂商插件契约。
*
* 两套实现(高德 / 百度)各自放在 provider/amap、provider/baidu 下,业务层只认这里的接口。
* 切换由 VITE_MAP_PROVIDER 决定,运行时只加载被选中厂商的 SDK script —— 不调另一家服务、
* 不渲染另一家底图。
*
* 这里刻意不 import 任何厂商类型:本文件是纯契约,两个厂商谁都不该在这里留下名字。
*/
import type { OverlayMap, OverlayRuntime } from '@hm/map-overlay';
/** 经纬度对。与厂商无关,业务层一律用这个口径 */
export type LngLat = [number, number];
export interface BasemapBounds {
getSouthWest(): { getLng(): number; getLat(): number };
getNorthEast(): { getLng(): number; getLat(): number };
}
/**
* 地图门面。补齐内核 OverlayMap 的四件事 + 业务在 MapStage 里实际用到的全部方法。
*
* 保留高德那套方法名(getSize/getBounds/setZoomAndCenter/on/off),百度侧做适配 ——
* 这样 MapStage 的几百行业务逻辑一个字不用改。
*/
export interface Basemap extends OverlayMap {
/** 原生地图实例,需要厂商特有能力时由 provider 内部自己断言,业务层不碰 */
readonly raw: unknown;
getBounds(): BasemapBounds;
setZoomAndCenter(
zoom: number,
center: LngLat,
immediately?: boolean,
duration?: number,
): void;
setMapStyle(style: string): void;
/** 屏幕像素 → 经纬度(区界命中测试用) */
containerToLngLat(pixel: [number, number]): { getLng(): number; getLat(): number };
on(event: string, handler: (e: any) => void): void;
off(event: string, handler: (e: any) => void): void;
destroy(): void;
/** 自绘层挂画布用的运行时(高德=AMap.CustomLayer,百度=自管画布) */
readonly overlayRuntime: OverlayRuntime;
}
/** 热力层统一接口:MapStage 只认这七个成员 */
export interface HeatLayerLike {
setDataset(lng: Int32Array, lat: Int32Array, count: Int32Array, keep?: Uint8Array | null): void;
clear(): void;
setStyle(style: Partial<{ radius: number; opacity: number }>): void;
setVisible(visible: boolean): void;
readonly count: number;
/** 归一化上限,聚合层数字浓淡读它,口径与底色一致 */
readonly maxWeight: number;
destroy(): void;
}
/** 加载失败/未配置的统一错误。code 保持旧值以兼容 MapKeyGuide */
export type MapErrorCode = 'NO_KEY' | 'LOAD_FAILED' | 'NO_HEATMAP';
export class MapError extends Error {
code: MapErrorCode;
hint: string;
constructor(code: MapErrorCode, message: string, hint: string) {
super(message);
this.name = 'MapError';
this.code = code;
this.hint = hint;
}
}
/** 每个 provider 模块必须导出的工厂入口 */
export interface MapProvider {
/** 供 UI 展示的厂商名 */
readonly name: string;
/** 加载 SDK 并创建地图门面。失败必须抛 MapError */
create(container: HTMLElement, opts: CreateOptions): Promise<Basemap>;
/** 构造热力层 */
createHeatLayer(basemap: Basemap): HeatLayerLike;
/** 当前厂商可用的底图样式选项 */
readonly basemapStyles: ReadonlyArray<{ label: string; value: string }>;
/** 默认底图样式 */
readonly defaultBasemap: string;
}
export interface CreateOptions {
zoom: number;
center: LngLat;
minZoom: number;
maxZoom: number;
basemap: string;
}
import { Panel, Field } from '@hm/ui'; import { Panel, Field } from '@hm/ui';
import { useHeatmapStore, isFilterDirty, type TimePreset } from '@/store/useHeatmapStore'; import { useHeatmapStore, isFilterDirty, type TimePreset } from '@/store/useHeatmapStore';
import { BASEMAP_OPTIONS } from '@/features/heatmap/map/palette'; import { BASEMAP_OPTIONS } from '@/features/heatmap/map/provider/registry';
import { UNRESOLVED_LABEL } from '@/features/heatmap/aggregate/types'; import { UNRESOLVED_LABEL } from '@/features/heatmap/aggregate/types';
import { DatePicker, Input, Segmented, Select, Switch, Button } from 'antd'; import { DatePicker, Input, Segmented, Select, Switch, Button } from 'antd';
import dayjs, { type Dayjs } from 'dayjs'; import dayjs, { type Dayjs } from 'dayjs';
...@@ -197,7 +197,7 @@ export function FilterPanel() { ...@@ -197,7 +197,7 @@ export function FilterPanel() {
} }
/** 选项表留在模块层:每次渲染现 map 一份,antd 会把整列选项重新比一遍 */ /** 选项表留在模块层:每次渲染现 map 一份,antd 会把整列选项重新比一遍 */
const BASEMAP_SELECT_OPTIONS = BASEMAP_OPTIONS.map((o) => ({ label: o.label, value: o.value })); const BASEMAP_SELECT_OPTIONS = BASEMAP_OPTIONS.map((o: { label: string; value: string }) => ({ label: o.label, value: o.value }));
/** /**
* 关键词那一栏。 * 关键词那一栏。
......
...@@ -17,8 +17,8 @@ import type { ...@@ -17,8 +17,8 @@ import type {
import type { ImportManifest } from '@/features/heatmap/data/importedDb'; import type { ImportManifest } from '@/features/heatmap/data/importedDb';
import type { ImportProgressInfo } from '@/features/heatmap/data/importProgress'; import type { ImportProgressInfo } from '@/features/heatmap/data/importProgress';
import { debugInitialOn } from '@/features/heatmap/debug/debugBus'; import { debugInitialOn } from '@/features/heatmap/debug/debugBus';
import { DEFAULT_BASEMAP } from '@/features/heatmap/map/palette'; import { DEFAULT_BASEMAP } from '@/features/heatmap/map/provider/registry';
import { DEFAULT_HEAT_STYLE } from '@/features/heatmap/map/HeatLayer'; import { DEFAULT_HEAT_STYLE } from '@/features/heatmap/map/heatReference';
import { buildPointRoster } from '@/features/heatmap/aggregate/viewSnapshot'; import { buildPointRoster } from '@/features/heatmap/aggregate/viewSnapshot';
import { import {
OPERATING_NON, OPERATING_NON,
...@@ -589,8 +589,8 @@ interface HeatmapState { ...@@ -589,8 +589,8 @@ interface HeatmapState {
progress: { file: string; ratio: number } | null; progress: { file: string; ratio: number } | null;
meta: MetaFile | null; meta: MetaFile | null;
detailReady: boolean; detailReady: boolean;
/** 高德 Key 未配置 / 加载失败时的引导信息 */ /** 当前地图厂商 Key 未配置 / 加载失败时的引导信息 */
amapError: { code: string; message: string; hint: string } | null; mapError: { code: string; message: string; hint: string } | null;
/** 当前数据来源:用户导入(持久化在 IndexedDB)or 空态(本地无任何数据集) */ /** 当前数据来源:用户导入(持久化在 IndexedDB)or 空态(本地无任何数据集) */
dataOrigin: 'empty' | 'imported'; dataOrigin: 'empty' | 'imported';
/** 导入数据集的清单,供顶栏展示「导入自 xxx.xlsx」与清除导入入口 */ /** 导入数据集的清单,供顶栏展示「导入自 xxx.xlsx」与清除导入入口 */
...@@ -795,7 +795,7 @@ interface HeatmapState { ...@@ -795,7 +795,7 @@ interface HeatmapState {
setProgress: (p: HeatmapState['progress']) => void; setProgress: (p: HeatmapState['progress']) => void;
setMeta: (m: MetaFile) => void; setMeta: (m: MetaFile) => void;
setDetailReady: (v: boolean) => void; setDetailReady: (v: boolean) => void;
setAmapError: (e: HeatmapState['amapError']) => void; setMapError: (e: HeatmapState['mapError']) => void;
setDataOrigin: (origin: HeatmapState['dataOrigin'], info?: ImportManifest | null) => void; setDataOrigin: (origin: HeatmapState['dataOrigin'], info?: ImportManifest | null) => void;
/** 加载后写入数据体检结论(meta.bounds 等写坏时给一句告警,正常为空) */ /** 加载后写入数据体检结论(meta.bounds 等写坏时给一句告警,正常为空) */
setDataWarn: (msg: string | null) => void; setDataWarn: (msg: string | null) => void;
...@@ -942,7 +942,7 @@ export const useHeatmapStore = create<HeatmapState>((set, get) => ({ ...@@ -942,7 +942,7 @@ export const useHeatmapStore = create<HeatmapState>((set, get) => ({
progress: null, progress: null,
meta: null, meta: null,
detailReady: false, detailReady: false,
amapError: null, mapError: null,
dataOrigin: 'empty', dataOrigin: 'empty',
importInfo: null, importInfo: null,
importProgress: null, importProgress: null,
...@@ -1022,7 +1022,7 @@ export const useHeatmapStore = create<HeatmapState>((set, get) => ({ ...@@ -1022,7 +1022,7 @@ export const useHeatmapStore = create<HeatmapState>((set, get) => ({
filter: { ...s.filter, from: meta.timeRange.min, to: meta.timeRange.max }, filter: { ...s.filter, from: meta.timeRange.min, to: meta.timeRange.max },
})), })),
setDetailReady: (detailReady) => set({ detailReady }), setDetailReady: (detailReady) => set({ detailReady }),
setAmapError: (amapError) => set({ amapError }), setMapError: (mapError) => set({ mapError }),
setDataOrigin: (dataOrigin, importInfo = null) => set({ dataOrigin, importInfo }), setDataOrigin: (dataOrigin, importInfo = null) => set({ dataOrigin, importInfo }),
setImportProgress: (importProgress) => set({ importProgress }), setImportProgress: (importProgress) => set({ importProgress }),
......
...@@ -25,6 +25,7 @@ ...@@ -25,6 +25,7 @@
"baseUrl": ".", "baseUrl": ".",
"paths": { "paths": {
"@/*": ["src/*"], "@/*": ["src/*"],
"@map-provider": ["src/features/heatmap/map/provider/baidu/index.ts"],
"@hm/ui": ["packages/ui/src/index.ts"], "@hm/ui": ["packages/ui/src/index.ts"],
"@hm/map-overlay": ["packages/map-overlay/src/index.ts"], "@hm/map-overlay": ["packages/map-overlay/src/index.ts"],
"@hm/clean-core": ["packages/clean-core/src/index.ts"], "@hm/clean-core": ["packages/clean-core/src/index.ts"],
......
import { defineConfig } from 'vite'; import { defineConfig, loadEnv } from 'vite';
import react from '@vitejs/plugin-react'; import react from '@vitejs/plugin-react';
import { fileURLToPath, URL } from 'node:url'; import { fileURLToPath, URL } from 'node:url';
import fs from 'node:fs'; import fs from 'node:fs';
...@@ -41,10 +41,31 @@ function dataReadinessPlugin(root: string) { ...@@ -41,10 +41,31 @@ function dataReadinessPlugin(root: string) {
}; };
} }
export default defineConfig({ export default defineConfig(({ mode }) => {
/**
* 地图厂商选择。默认 baidu —— 本项目只有百度商授。
*
* VITE_MAP_PROVIDER 在 Vite 配置阶段从 .env.* 读入(不是 import.meta.env,那是浏览器侧的)。
* alias 把 @map-provider 固定指向选中目录:未选中的厂商连模块图都进不去,
* 产物里不会有它的加载器、不会请求它的 SDK script。
*/
const env = loadEnv(mode, process.cwd(), 'VITE_');
const provider = (env.VITE_MAP_PROVIDER ?? 'baidu').trim();
if (provider !== 'baidu' && provider !== 'amap') {
throw new Error(
`[map] VITE_MAP_PROVIDER 只接受 'baidu' | 'amap',收到 '${provider}'。`,
);
}
const providerDir = fileURLToPath(
new URL(`./src/features/heatmap/map/provider/${provider}`, import.meta.url),
);
return {
plugins: [react(), dataReadinessPlugin(process.cwd())], plugins: [react(), dataReadinessPlugin(process.cwd())],
resolve: { resolve: {
alias: { alias: {
// 地图插件:只暴露被选中的那一家
'@map-provider': providerDir,
'@': fileURLToPath(new URL('./src', import.meta.url)), '@': fileURLToPath(new URL('./src', import.meta.url)),
// 组件库源码直引:即使 workspace 软链异常,dev / 构建也能解析 // 组件库源码直引:即使 workspace 软链异常,dev / 构建也能解析
'@hm/ui': fileURLToPath(new URL('./packages/ui/src/index.ts', import.meta.url)), '@hm/ui': fileURLToPath(new URL('./packages/ui/src/index.ts', import.meta.url)),
...@@ -185,4 +206,5 @@ export default defineConfig({ ...@@ -185,4 +206,5 @@ export default defineConfig({
worker: { worker: {
format: 'es', format: 'es',
}, },
};
}); });
...@@ -5,6 +5,10 @@ export default defineConfig({ ...@@ -5,6 +5,10 @@ export default defineConfig({
resolve: { resolve: {
alias: { alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)), '@': fileURLToPath(new URL('./src', import.meta.url)),
// 与 vite.config.ts / tsconfig.json 保持一致:测试默认跑百度 provider
'@map-provider': fileURLToPath(
new URL('./src/features/heatmap/map/provider/baidu/index.ts', import.meta.url),
),
'@hm/ui': fileURLToPath(new URL('./packages/ui/src/index.ts', import.meta.url)), '@hm/ui': fileURLToPath(new URL('./packages/ui/src/index.ts', import.meta.url)),
'@hm/map-overlay': fileURLToPath( '@hm/map-overlay': fileURLToPath(
new URL('./packages/map-overlay/src/index.ts', import.meta.url), new URL('./packages/map-overlay/src/index.ts', import.meta.url),
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!