loadAmap.ts 4.28 KB
/**
 * 高德 JS API 2.0 动态加载。
 *
 * 用外链 script 而不是 npm 包:高德官方只提供 CDN 脚本,任何"npm 版高德地图"
 * 都是第三方二次封装,升级与排障都不受控。
 *
 * 三个坑,都在这里处理掉:
 *   1) 2021-12-02 之后申请的 Key 必须配 securityJsCode,否则报 INVALID_USER_SCODE;
 *   2) Key 必须绑定当前访问域名,否则报 INVALID_USER_DOMAIN 且地图区域一片白;
 *   3) v1.4 里热力图类叫 AMap.Heatmap,v2 里叫 AMap.HeatMap —— 大小写不同。
 *      不写死类名,运行期取存在的那个,避免跟着文档版本换写法。
 *
 * 热力层使用高德原生 AMap.HeatMap 插件:必须在加载时声明 plugin,
 * 且要在 plugin 回调返回后再 new(见 HeatLayer.ensure)。
 */

export type AmapErrorCode = 'NO_KEY' | 'LOAD_FAILED' | 'NO_HEATMAP';

export class AmapError extends Error {
  code: AmapErrorCode;
  hint: string;

  constructor(code: AmapErrorCode, message: string, hint: string) {
    super(message);
    this.name = 'AmapError';
    this.code = code;
    this.hint = hint;
  }
}

export interface AmapConfig {
  key: string;
  securityCode: string;
  configured: boolean;
}

export function getAmapConfig(): AmapConfig {
  const key = (import.meta.env.VITE_AMAP_KEY ?? '').trim();
  const securityCode = (import.meta.env.VITE_AMAP_SECURITY_CODE ?? '').trim();
  return { key, securityCode, configured: key.length > 0 };
}

const PLUGIN_NAMES = ['AMap.HeatMap'];

let loading: Promise<typeof AMap> | null = null;

export function loadAmap(): Promise<typeof AMap> {
  if (loading) return loading;

  loading = new Promise<typeof AMap>((resolve, reject) => {
    const cfg = getAmapConfig();
    if (!cfg.configured) {
      reject(
        new AmapError(
          'NO_KEY',
          '未配置高德地图 Key',
          '把 .env.example 复制成 .env.local,填入 VITE_AMAP_KEY 与 VITE_AMAP_SECURITY_CODE 后重启 dev server。Key 需为「Web端(JS API)」类型,并绑定 localhost / 127.0.0.1。',
        ),
      );
      return;
    }

    if (window.AMap) {
      resolve(window.AMap);
      return;
    }

    if (cfg.securityCode) {
      window._AMapSecurityConfig = { securityJsCode: cfg.securityCode };
    }

    const src =
      `https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(cfg.key)}` +
      `&plugin=${PLUGIN_NAMES.join(',')}`;

    const script = document.createElement('script');
    script.src = src;
    script.async = true;
    script.crossOrigin = 'anonymous';

    const timer = window.setTimeout(() => {
      reject(
        new AmapError(
          'LOAD_FAILED',
          '高德 JS API 加载超时',
          '检查网络是否可访问 webapi.amap.com;内网环境需要把该域名加入白名单。',
        ),
      );
    }, 15000);

    script.onload = () => {
      window.clearTimeout(timer);
      const amap = window.AMap;
      if (!amap) {
        reject(new AmapError('LOAD_FAILED', '脚本已加载但未挂载 window.AMap', ''));
        return;
      }
      // URL 里已声明 plugin,这里再补一次:某些内网代理会吞掉 query 参数
      amap.plugin(PLUGIN_NAMES, () => resolve(amap));
    };

    script.onerror = () => {
      window.clearTimeout(timer);
      reject(
        new AmapError(
          'LOAD_FAILED',
          '高德 JS API 脚本加载失败',
          '常见原因:无外网、企业网络拦截 webapi.amap.com、或 Key 被限制。可打开浏览器控制台查看高德返回的错误码。',
        ),
      );
    };

    document.head.appendChild(script);
  });

  return loading;
}

/** 运行期解析热力图构造函数,抹平 v1/v2 的类名差异 */
export function resolveHeatMapCtor(): typeof AMap.HeatMap {
  const amap = window.AMap as unknown as Record<string, unknown> | undefined;
  const ctor = amap?.HeatMap ?? amap?.Heatmap;
  if (typeof ctor !== 'function') {
    throw new AmapError(
      'NO_HEATMAP',
      '当前 Key 未加载 AMap.HeatMap 插件',
      '请确认 Key 申请时勾选了「Web端(JS API)」并开通了热力图插件权限。',
    );
  }
  return ctor as typeof AMap.HeatMap;
}

/** 深圳默认视野。数据范围是深圳全域,初始按这个中心铺开 */
export const SHENZHEN_VIEW = {
  center: [114.06, 22.62] as [number, number],
  zoom: 11,
};