BaiduBasemap.ts 12.7 KB
/**
 * 百度地图门面 + 自绘层运行时。
 *
 * 自绘层为什么不用百度原生 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。
 * ⚠️ 但 4.0 的 getBounds()/overlayPixelToPoint() 在 BD09 CRS 下绕过全局声明,
 * 出参仍是 BD-09(getCenter()/pointToOverlayPixel() 则是 GCJ-02)。门面统一在这里补正,
 * 否则取数框会比可视区偏东北约 600m,拖到下半屏的聚合点与热力核会整批消失。
 */

import type { OverlayLayerLike, OverlayRuntime } from '@hm/map-overlay';
import type { Basemap, BasemapBounds, LngLat } from '../types';
import { bd09ToGcj02 } from './coord';
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?: (force?: boolean) => void;
  private map: BaiduGLMap | null = null;
  private raf = 0;
  private readonly zIndex: number;
  /** 每个事件一个稳定引用,removeEventListener 要用同一个函数 */
  private readonly handlers = new Map<string, () => void>();

  private handlerFor(event: string): () => void {
    const settled = this.SETTLED_EVENTS.includes(event);
    return () => this.onViewChange(settled);
  }

  constructor(
    private readonly canvas: HTMLCanvasElement,
    opts: { zIndex: number; zooms: [number, number]; alwaysRender: boolean },
  ) {
    this.zIndex = opts.zIndex;
  }

  /**
   * 事件到 → 合并到下一帧点一次名。rAF 只在这里按需起,不是常驻。
   *
   * ⚠️ 落定事件(zoomend/moveend/resize)不能和动画帧共用"已有 rAF 就跳过"的合并逻辑:
   * 滚轮/拖动期间 moving/zooming 每帧都排队,落定那一刻 rAF 往往还占着,若照样 return,
   * 这一帧就被吞了;而百度在 zoomend 之后还有一次自己的收尾渲染,会把自绘画布盖住 ——
   * 现场表现就是"滚轮滚动时能看到点,一停下来点必然消失"(2026-11-24 实测)。
   * 所以落定事件单独排一帧,并带 force 让内核绕过"视图没变"的跳过判定。
   */
  private readonly onViewChange = (settled: boolean): void => {
    if (!settled) {
      if (this.raf) return;
      this.raf = requestAnimationFrame(() => {
        this.raf = 0;
        this.render?.();
      });
      return;
    }
    // 落定帧:另起一条 rAF,等百度那帧收尾渲染之后再画,确保覆盖在最上层。
    if (this.raf) {
      cancelAnimationFrame(this.raf);
      this.raf = 0;
    }
    this.raf = requestAnimationFrame(() => {
      this.raf = 0;
      this.render?.(true);
      // 百度个别情况下收尾渲染比这条 rAF 还晚一帧;再补一帧兜底,幂等且只有落定时才付。
      requestAnimationFrame(() => this.render?.(true));
    });
  };

  private readonly VIEW_EVENTS = ['moving', 'zooming', 'moveend', 'zoomend', 'resize'];
  /** 落定事件:动画停下的那一帧,必须强制重画(理由见 onViewChange) */
  private readonly SETTLED_EVENTS = ['moveend', 'zoomend', 'resize'];

  setMap(target: unknown | null): void {
    if (target) {
      // 内核 defineOverlay 会在挂载前把宿主门面的 raw 解包出来(见 overlay.ts mount),
      // 所以正常路径收到的就是原生 BMapGL.Map。这里再兜一层:万一有人绕过内核
      // 直接把门面传进来,仍能取到 raw;两条路都没有就明确报错,别让它变成
      // "getContainer is not a function" 那种难以定位的崩溃。
      const facade = target as { raw?: BaiduGLMap };
      const map = facade.raw ?? (target as BaiduGLMap);
      if (typeof map.getContainer !== 'function') {
        throw new Error('BaiduCanvasLayer.setMap: 收到的不是百度原生地图,取不到 getContainer');
      }
      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) {
        const handler = this.handlerFor(event);
        map.addEventListener(event, handler);
        this.handlers.set(event, handler);
      }
      // 挂载后点一帧:否则第一次数据到位前画布空白
      this.onViewChange(false);
    } else {
      if (this.raf) cancelAnimationFrame(this.raf);
      this.raf = 0;
      if (this.map) {
        for (const event of this.VIEW_EVENTS) {
          const handler = this.handlers.get(event);
          if (handler) this.map.removeEventListener(event, handler);
        }
      }
      this.handlers.clear();
      this.canvas.remove();
      this.map = null;
    }
  }

  show(): void {
    this.canvas.style.display = '';
  }
  hide(): void {
    this.canvas.style.display = 'none';
  }
}

/**
 * 百度 GL 4.0 的等效瓦片尺寸。
 *
 * 百度的缩放单位不是标准 256 瓦片墨卡托:MercatorProjection.getZoomUnits(z)=2^(18-z),
 * 于是每度像素 = (世界周长 / 2^18) × 2^z / 360,对应 tileSize = 40075016.686 / 2^18
 * ≈ 152.874。实测 z8~z15 与 pointToOverlayPixel 逐点投影误差 < 0.01px(2026-11-24)。
 *
 * 自绘层(聚合点/热点/区界/调试画布)原先共用 APP_SCALE 的 256,点位相对中心被放大
 * 256/152.874≈1.675 倍 → 拖动越远错得越多、拖一次跑一点、像叠了两个地图。
 * 门面挂出这个口径,内核所有 frame.set 统一读它;高德门面不挂,仍走 256。
 */
export const BAIDU_TILE_SIZE = 40075016.68557849 / Math.pow(2, 18);

const WORLD_CIRCUMFERENCE = 40075016.68557849;
/** 标定斜率用的纬度跨度。深圳全境 ±0.5° 内斜率近似线性,取 ±0.1° 足够稳 */
const SLOPE_PROBE_LAT = 22.62;
const SLOPE_PROBE_D = 0.1;

/** 标准球形墨卡托的对数纬度(与 @hm/map-overlay 的 mercY 同一支公式) */
function standardMercY(latDeg: number): number {
  return Math.log(Math.tan(Math.PI / 4 + (Math.max(-85, Math.min(85, latDeg)) * Math.PI) / 360));
}

/**
 * 百度椭圆投影相对标准墨卡托的纬度斜率。
 *
 * 用百度自己的 MercatorProjection 在城市中心标定:把它的米制 Y 归一化成与 mercY 同量纲,
 * 再取局部斜率。实测深圳 22~23° 全域用这一个因子误差 < 1px(2026-11-24)。
 */
function baiduLatSlope(B: BaiduGLNamespace): number {
  const Ctor = B.MercatorProjection;
  if (!Ctor) return 1;
  const proj = new Ctor();
  const norm = (lat: number): number =>
    (proj.lngLatToMercator({ lng: 114.06, lat } as BaiduGLPoint).lat * 2 * Math.PI) /
    WORLD_CIRCUMFERENCE;
  const up = SLOPE_PROBE_LAT + SLOPE_PROBE_D;
  const down = SLOPE_PROBE_LAT - SLOPE_PROBE_D;
  const slope = (norm(up) - norm(down)) / (standardMercY(up) - standardMercY(down));
  return Number.isFinite(slope) && slope > 0 ? slope : 1;
}

export class BaiduBasemap implements Basemap {
  readonly raw: BaiduGLMap;
  /** BMapGL 命名空间;厂商内部的图层工厂从这里取构造器 */
  readonly gl: BaiduGLNamespace;
  readonly overlayRuntime: OverlayRuntime;
  /** 自绘层投影口径,见上方推导 */
  readonly frameScale: { tileSize: number; referenceLat: number; latSlope: number };

  /** 出参是否仍带着 BD-09(见文件头);只在全局 GCJ + BD09 CRS 这一组合下成立 */
  private readonly outputIsBd09: boolean;

  constructor(
    private readonly B: BaiduGLNamespace,
    map: BaiduGLMap,
  ) {
    this.raw = map;
    this.gl = B;
    const crsRaw = map as BaiduGLMap & { getCRS?: () => string };
    const crs = typeof crsRaw.getCRS === 'function' ? crsRaw.getCRS() : '';
    this.outputIsBd09 = B.coordType === 'BMAP_COORD_GCJ02' && (!crs || crs.includes('BD09'));
    this.frameScale = {
      tileSize: BAIDU_TILE_SIZE,
      referenceLat: 22.5,
      latSlope: baiduLatSlope(B),
    };
    this.overlayRuntime = {
      CustomLayer: BaiduCanvasLayer as unknown as OverlayRuntime['CustomLayer'],
      // 百度不像高德那样逐帧回调 CustomLayer.render,只在视图事件里点名。
      // 声明 false 后内核 schedule() 会自己排 rAF 兑现数据/落定后的重绘,
      // 否则滚轮停下那帧之后聚合数字会消失且不再回来。
      perFrameRender: false,
    };
  }

  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 };
  }
  /** 百度"出参"两条 API 的坐标口径补正;入参(pointToOverlayPixel)本来就是 GCJ,不动 */
  private toUserPoint(p: BaiduGLPoint): { getLng(): number; getLat(): number } {
    if (!this.outputIsBd09) return { getLng: () => p.lng, getLat: () => p.lat };
    const [lng, lat] = bd09ToGcj02(p.lng, p.lat);
    return { getLng: () => lng, getLat: () => lat };
  }

  containerToLngLat(pixel: [number, number]) {
    const p: BaiduGLPoint = this.raw.overlayPixelToPoint(
      new this.B.Pixel(pixel[0], pixel[1]) as BaiduGLPixel,
    );
    return this.toUserPoint(p);
  }
  getBounds(): BasemapBounds {
    const b = this.raw.getBounds();
    const sw = this.toUserPoint(b.getSouthWest());
    const ne = this.toUserPoint(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,
  ) {
    // 百度 GL 没有高德那套 setZoomAndCenter(脚本里搜不到这个方法名),取景入口是
    // centerAndZoom(point, zoom, opts)。immediately 映射到 opts.noAnimation;
    // duration 百度 GL 不支持,业务侧的 300~400ms 动画在这里退化为 SDK 默认行为。
    // 之前直接透传 setZoomAndCenter 会抛 "is not a function",取景一触发就白屏。
    this.raw.centerAndZoom(
      new this.B.Point(center[0], center[1]) as BaiduGLPoint,
      zoom,
      { noAnimation: immediately === true },
    );
  }
  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';
}