districtShapes.ts 19.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
/**
 * 行政区边界(区界)数据。
 *
 * 来源:高德行政区边界(DistrictSearch)导出的 GeoJSON,作为**常驻静态资源**放在
 * `public/geo/shenzhen.geojson`(提交进仓库,随构建产物走,不依赖任何数据生成步骤)。
 * 运行期由 `ensureDistrictShapes()` 直接 fetch `/geo/shenzhen.geojson` 加载 ——
 * 它是地图底图的参考几何,与「出险数据集」解耦:出险数据必须导入、项目不内置,
 * 但行政区边界是底图的一部分,始终在场(导入数据前后都能用)。
 *
 * 这一层为什么单独存在(而不是图层自己 fetch 一份 JSON 顺手画):
 *
 * 1) **名称必须对上字典**。界面上的区名读的是 `meta.dict.districts`(导入数据时由地址解析
 *    生成),边界文件读的是行政区全称。两边对不上就是「涂了一块不知道是谁的区界」,
 *    而这块屏上没有一个字会说「对不上」,只会让人觉得数错了。所以匹配在这里一次做完,
 *    并把「字典里有、边界里没有」的名单交出去(大鹏新区、未识别),界面据此说明为什么涂不出。
 * 2) **点在哪一个区,得由边界算**。区界聚焦里点一块区域要开该区的清单,
 *    命中判定用真实多边形(射线法,含洞),不是拿 bbox 或质心距离凑 ——
 *    深圳的区界是凹的,bbox 判据会把隔壁区的案子算进这一档。
 * 3) 边界几何是数据而不是画法,所以它能被单测钉住(见 districtShapes.test.ts)。
 *
 * ⚠️ 街道级边界目前不在这里:文件只到区级(level=district、childrenNum=0),
 *    而高德只给到区一级 —— 官方文档写明「街道级别不能返回边界数据 polyline」,公开那份区级产物
 *    往下也没有切片。所以街道档的形状仍然是「照出险落点反推」(见 map/spotlightGeometry.ts),
 *    不假装是行政边界。要换成真实街道界的取法、核验与接入改动,见 docs/街道边界取法.md。
 */

import { UNRESOLVED_LABEL } from '../aggregate/types';
import { M_PER_DEG_LAT, M_PER_EQUATOR } from '../map/hotspotGeometry';
import { parseDistrictGeometry, parseGeoFeatures, parseGeometryPolys } from '@hm/clean-core';
import { pointInPolygon, type LngLat, type NamedPolys, type ShapePolygon } from './polygon';

/**
 * 几何判定只有一份实现,在 `geo/polygon.ts`。
 *
 * 这里转出去是因为 `SpotlightLayer` 与单测本来就从这个模块取 `pointInPolygon` /
 * `LngLat` / `ShapePolygon`;保留原导出路径,但实现不再复制一份 ——
 * 导入清洗(跑在 Worker 里)与本文件的区界聚焦必须用同一个射线法,
 * 否则会出现「清洗判它落在区外剔掉了,区界聚焦里点它又算区内」这种自己打自己的账。
 */
export { pointInPolygon };
export type { LngLat, ShapePolygon, NamedPolys };

/** 一块地理范围(真实度数)。字段与图层、取景用的是同一套名字 */
export interface ShapeBounds {
  minLng: number;
  maxLng: number;
  minLat: number;
  maxLat: number;
}

/** 一个区的边界(多边形的形状定义在 geo/polygon.ts) */
export interface DistrictShape {
  /** 区字典下标(meta.dict.districts),与统计、筛选、清单同一套下标 */
  idx: number;
  /** 字典里的那一支名字(界面念的是它,不是文件里的全称) */
  name: string;
  /** 文件里的行政区代码,只用于对账与排查数据来源,不上界面 */
  adcode: string;
  /** 一个区可能有多块(南山 4 块、宝安 / 龙岗各 2 块:离岛与飞地) */
  polys: ShapePolygon[];
  /** 所有块的并集范围,取景用 */
  bbox: ShapeBounds;
  /**
   * 面积(平方公里,外环减洞)。
   *
   * 区界那一片的深浅按**单位面积案件数**涂,不按起数:起数涂满整片边界就是典型的
   * 「等值线地图骗人」—— 龙岗区的面积是罗湖的好几倍,同样涂「起数最多」那一档,
   * 看的人读到的是「龙岗比罗湖危险」,而那两个数讲的其实是「龙岗总共多了几起」
   * 和「罗湖每平方公里挤了几起」两件不同的事。牌子念的仍是起数(那一维榜上就是这么排的),
   * 深浅讲密度,图例上写清这一句。
   */
  areaKm2: number;
  /**
   * 牌子落点。
   *
   * 优先用文件里的 centroid(高德给的是「面」的中心,不是 bbox 中心),
   * 但它偶尔会掉在区界外面(凹得厉害的形状会),那种情况退回最大那块多边形里
   * 最靠中间的一个真实顶点 —— 宁可牌子压在边界上,也不要飘在隔壁区或者海里,
   * 因为那块牌子指认的就是「这一片是它」。
   */
  anchor: LngLat;
}

/** 一次匹配的结果:涂得出的那些,加上两个方向的缺口 */
export interface DistrictShapeMatch {
  shapes: DistrictShape[];
  /** 字典里有名有姓、边界文件里却没有的那几个(大鹏新区、未识别)。界面必须交代为什么涂不出 */
  withoutShape: string[];
  /** 文件里有、字典里对不上的那几个(名称写法变了,或多取了一个层级)。不画,只报出来 */
  extraInFile: string[];
}

/* ------------------------------- 解析与匹配 ------------------------------- */

/**
 * 把边界文件里的要素对上区字典。
 *
 * 只按名称对上,不按 adcode 对上:字典里根本没有 adcode 这一列(区名是从地址第 3 段读的),
 * 而地址写的是「深圳市龙岗区」这样的名称。名称是对得上就认,认不上就报出来 ——
 * 硬造一张「440307→某区」的表等于在界面上多养一份谁也没核对过的映射。
 */
/**
 * 把边界文件解析成「名字 + 几何」,不做任何名字匹配。
 *
 * **实现在 `@hm/clean-core`**(`geo/offshoreVerdict.ts`),这里只再导出。这个入口是给
 * **导入清洗**用的:清洗跑在解析 Worker / Node CLI 里,只关心「这个点在不在这一堆多边形里」,
 * 不关心区名与字典对不对得上(那是主线程画区界时才有的事)。
 *
 * 解码规则(`parseGeoFeatures` / `parseGeometryPolys`)也只有包内一份,本文件的
 * `matchDistrictShapes` 同样从包里取 —— 尤其 MultiPolygon 按块分组那一条,
 * 漏了就是整块判不进去(大鹏半岛曾被判成 504 条域外,见包内注释)。
 */
export { parseDistrictGeometry };

export function matchDistrictShapes(raw: unknown, districtNames: string[]): DistrictShapeMatch {
  const shapes: DistrictShape[] = [];
  const matchedNames = new Set<string>();
  const extraInFile: string[] = [];

  for (const feature of parseGeoFeatures(raw)) {
    const name = typeof feature.name === 'string' ? feature.name.trim() : '';
    const polys = parseGeometryPolys(feature.geometry);
    if (!name || polys.length === 0) continue;
    const idx = districtNames.indexOf(name);
    if (idx < 0) {
      // 文件里有、字典里没有:多半是名称写法变了(例如「宝安区」写成「深圳市宝安区」)
      // 或者多取了一个层级(市、省)。画上去就是把别人的案子涂到这块界里,所以只报不画。
      if (!extraInFile.includes(name)) extraInFile.push(name);
      continue;
    }
    if (matchedNames.has(name)) continue; // 同名只取第一块,重复要素不该把起数画两遍
    matchedNames.add(name);
    shapes.push(
      buildShape(idx, name, String(feature.adcode ?? ''), polys, readPoint(feature.centroid)),
    );
  }

  const withoutShape = districtNames.filter(
    (n) => n.length > 0 && n !== UNRESOLVED_LABEL && !matchedNames.has(n),
  );
  return { shapes, withoutShape, extraInFile };
}

/**
 * 「未识别」不进 withoutShape:它不是一个行政区,而是「地址读不出区」的记号,
 * 本来就不该有边界(见 types.UNRESOLVED_LABEL)。把它混进「没有区界的区」,
 * 等于在界面上给它发了一张地户口。
 */

/** 高德给的 centroid / center 是 [经度, 纬度];不是两个有限数就当没有(宁可退回顶点) */
function readPoint(raw: unknown): LngLat | null {
  if (!Array.isArray(raw) || raw.length < 2) return null;
  const lng = Number(raw[0]);
  const lat = Number(raw[1]);
  if (!Number.isFinite(lng) || !Number.isFinite(lat)) return null;
  return [lng, lat];
}

function buildShape(
  idx: number,
  name: string,
  adcode: string,
  polys: ShapePolygon[],
  centroid: LngLat | null,
): DistrictShape {
  const bbox: ShapeBounds = {
    minLng: Infinity,
    maxLng: -Infinity,
    minLat: Infinity,
    maxLat: -Infinity,
  };
  for (const p of polys) {
    for (const ring of p.rings) {
      for (const [lng, lat] of ring) {
        if (lng < bbox.minLng) bbox.minLng = lng;
        if (lng > bbox.maxLng) bbox.maxLng = lng;
        if (lat < bbox.minLat) bbox.minLat = lat;
        if (lat > bbox.maxLat) bbox.maxLat = lat;
      }
    }
  }
  return {
    idx,
    name,
    adcode,
    polys,
    bbox,
    anchor: pickAnchor(polys, bbox, centroid),
    areaKm2: polygonsAreaKm2(polys),
  };
}

/**
 * 一块边界的面积(平方公里)。
 *
 * 用等距圆柱近似(与热点、聚合那套米↔度换算同一口径,见 map/hotspotGeometry):
 * 每条环按自己的中心纬度换算东西距离,鞋带求面积,外环取正、洞取负。
 * 区界这个尺度上,椭球面积与它的差远小于边界本身的取点精度,不值得为此起一套地理库。
 *
 * 先减去洞再取正:万一某条外环自己也画成负方向(鞋带的符号跟绕行方向有关),
 * Math.abs 只保面积不保方向,洞那几条照样被减掉。
 */
export function polygonsAreaKm2(polys: ShapePolygon[]): number {
  let km2 = 0;
  for (const p of polys) {
    const outer = p.rings[0];
    if (!outer) continue;
    let area = ringAreaM2(outer);
    for (let i = 1; i < p.rings.length; i += 1) area -= ringAreaM2(p.rings[i]);
    km2 += Math.max(area, 0) / 1e6;
  }
  return km2;
}

/** 一条环的面积(平方米,绝对值)。平移到环自己的中心再算,避免大数相减丢精度 */
function ringAreaM2(ring: LngLat[]): number {
  let refLng = 0;
  let refLat = 0;
  for (const [lng, lat] of ring) {
    refLng += lng;
    refLat += lat;
  }
  refLng /= ring.length;
  refLat /= ring.length;
  // 1° 经线的米数随纬度收缩,取这一环自己的中心纬度换算
  const kx = M_PER_EQUATOR * Math.cos((refLat * Math.PI) / 180);

  let s = 0;
  for (let i = 1; i < ring.length; i += 1) {
    const x0 = (ring[i - 1][0] - refLng) * kx;
    const y0 = (ring[i - 1][1] - refLat) * M_PER_DEG_LAT;
    const x1 = (ring[i][0] - refLng) * kx;
    const y1 = (ring[i][1] - refLat) * M_PER_DEG_LAT;
    s += x0 * y1 - x1 * y0;
  }
  return Math.abs(s) / 2;
}

/** 环的鞋带面积(平方度,只用来在同一纬度上比大小,不拿去换算亩数) */
function ringArea(ring: LngLat[]): number {
  let s = 0;
  for (let i = 1; i < ring.length; i += 1) {
    const [x0, y0] = ring[i - 1];
    const [x1, y1] = ring[i];
    s += x0 * y1 - x1 * y0;
  }
  return Math.abs(s) / 2;
}

/**
 * 牌子落点:先用文件里的 centroid,落在区界外面才退回顶点。
 *
 * centroid 是高德按「面」给的中心,比 bbox 中心贴实际形状(龙岗这种带飞地的,
 * bbox 中心会掉到隔壁区去)。但它不保证在界内 —— 凹得厉害的形状会给到外面,
 * 而牌子一旦飘到隔壁区或海里,指认的就是别人的地盘,所以这里用同一套射线法验一次:
 * 在界内就用,不在就退回最大那块里最靠中间的那个真实顶点(顶点一定在自己界上)。
 */
function pickAnchor(polys: ShapePolygon[], bbox: ShapeBounds, centroid: LngLat | null): LngLat {
  if (centroid && polys.some((p) => pointInPolygon(centroid[0], centroid[1], p))) {
    return centroid;
  }
  let best: LngLat[] | null = null;
  let bestArea = -1;
  for (const p of polys) {
    const outer = p.rings[0];
    if (!outer) continue;
    const a = ringArea(outer);
    if (a > bestArea) {
      bestArea = a;
      best = outer;
    }
  }
  if (!best) return [(bbox.minLng + bbox.maxLng) / 2, (bbox.minLat + bbox.maxLat) / 2];
  // 最大那块里最靠近它自己 bbox 中心的那个顶点:一定在边界上,因此不会飘到别处去
  const cx = (best[0][0] + best.reduce((m, p) => Math.max(m, p[0]), -Infinity)) / 2;
  const cy = (best[0][1] + best.reduce((m, p) => Math.max(m, p[1]), -Infinity)) / 2;
  let bx = cx;
  let by = cy;
  let bd = Infinity;
  for (const [lng, lat] of best) {
    const d = (lng - cx) ** 2 + (lat - cy) ** 2;
    if (d < bd) {
      bd = d;
      bx = lng;
      by = lat;
    }
  }
  return [bx, by];
}

/* ------------------------------- 命中判定 ------------------------------- */

/**
 * 这一处落点属于哪一个区(多块里任何一块算一个区,飞地也是它的地)。
 *
 * 判定本身在 `geo/polygon.ts`(射线法 + 洞的处理,含那条踩过的坑:
 * MultiPolygon 必须按块分组,把第二块的外环当「洞」会整块判不进去)。
 */
export function districtAtPoint(shape: DistrictShape, lng: number, lat: number): boolean {
  return shape.polys.some((p) => pointInPolygon(lng, lat, p));
}

/* ------------------------------- 加载与缓存 ------------------------------- */

const BASE = import.meta.env.BASE_URL ?? '/';

/** 原始文件只拉一次;匹配结果按字典名单缓存(名单换了就得重配,不能拿旧的对应) */
let raw: unknown | null = null;
let pending: Promise<boolean> | null = null;
let lastNames: string[] | null = null;
let lastMatch: DistrictShapeMatch | null = null;

/**
 * 预热区界数据。返回是否可用(拉到并解析成功)。
 *
 * 失败不当致命错误处理:区界只服务「区界聚焦」这一个入口,拿不到就退回到
 * 按落点反推的那几档,入口自己说明为什么点不动。首屏不该为了一个可选图层多等一次请求。
 */
export function ensureDistrictShapes(): Promise<boolean> {
  if (raw) return Promise.resolve(true);
  if (!pending) {
    pending = (async () => {
      const res = await fetch(`${BASE}geo/shenzhen.geojson`, {
        credentials: 'same-origin',
      });
      if (!res.ok) throw new Error(`加载区界失败:HTTP ${res.status}`);
      const json = (await res.json()) as unknown;
      matchDistrictShapes(json, []); // 先验一次格式,坏数据在这一步就抛出来
      raw = json;
      return true;
    })().catch((err) => {
      console.warn('[geo] 区界数据未就绪,区界聚焦暂不可用:', err);
      pending = null;
      return false;
    });
  }
  return pending;
}

/** 区界是否已经可用(入口据此决定点得动还是点不动) */
export function hasDistrictShapes(): boolean {
  return raw !== null;
}

/**
 * 给**导入清洗**用的一份几何:不要求跟区字典对得上,直接把整份 FeatureCollection
 * 解析成 `{ name, polys, bbox }[]`。清洗只关心「这个点在不在这一堆多边形里」,
 * 不关心名字与字典的匹配(那是主线程画区界时才有的事,见 matchDistrictShapes)。
 *
 * 数据还没到位返回 null —— 不返回空数组冒充「就是没有边界」,否则离线/拉取失败时
 * 清洗会误以为「全深圳都没有边界」,把每一条都判成落水。
 */
export function allDistrictShapes(): NamedPolys[] | null {
  return raw ? parseDistrictGeometry(raw) : null;
}

/* ------------------------------- 落水 / 域外判定 ------------------------------- */

/**
 * `offshoreVerdict` 的**实现在 `@hm/clean-core`**(`geo/offshoreVerdict.ts`),这里只再导出。
 *
 * 为什么不能再留一份:这条判据同时被「导入清洗(Worker / CLI)」和「区界聚焦(主线程)」用,
 * 两份实现的偏差不会报错,只会静默地对同一条案子给出两个答案。
 *
 * 判据本身要交代清楚(改算法去包内改,但这几条约束不能丢):
 *   - 与 C 类(邻市,纯地址文本)是**两套互补**口径,不重叠:C 类管「地址写明外市」
 *     (东莞市 / 凤岗镇),坐标不参与;这里管「地址写深圳、坐标却不在任何陆域多边形内」。
 *   - ⚠️ **绝不**反过来用「坐标不在深圳」推断邻市。旧版清洗正是这么干的,结果地址写着
 *     「东莞市-凤岗镇」的案子因为每行都套「广东省-深圳市-」前缀被误判成深圳、塞进「海域」类,
 *     邻市永远 0 条。这里只回答「坐标在不在陆域」,归属仍交给 C 类文本。
 *   - ⚠️ 掩膜必须是**真正的陆地(海岸线)多边形**,不是行政区边界:AMap 行政区边界
 *     (shenzhen.geojson、440300)把沿海区水域也划进区界,实测龙岗 / 南山 / 市界 polygon
 *     都包住了大鹏外海与深圳湾,「在不在行政区多边形内」分不出海上点(见 offshore.test.ts 的对照)。
 *     所以 `offshoreShapes()` 优先取 `shenzhen-land.geojson`,没有时才降级到行政区边界
 *     (降级路径只能抓市域外点,抓不到沿海 / 内湾水域 —— 已知局限,不是 bug)。
 *   - 点落在掩膜覆盖框之外时返回 `judged: false`(无法判定,不标不剔),
 *     不按陆地处理 —— 旧版这么做漏判了南边 22.25 以下的海域。
 */
export { offshoreVerdict } from '@hm/clean-core';

/* ------------------------------- 陆地掩膜加载 ------------------------------- */

const LAND_BASE = import.meta.env.BASE_URL ?? '/';

/**
 * 陆地掩膜(海岸线,不含水域)的加载。优先 `geo/shenzhen-land.geojson`;
 * 没有(旧部署 / 离线)就返回 false,调用方降级到行政区边界(`allDistrictShapes`)。
 */
let landRaw: unknown | null = null;
let landPending: Promise<boolean> | null = null;

export function ensureLandMask(): Promise<boolean> {
  if (landRaw) return Promise.resolve(true);
  if (!landPending) {
    landPending = (async () => {
      try {
        const res = await fetch(`${LAND_BASE}geo/shenzhen-land.geojson`, {
          credentials: 'same-origin',
        });
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        landRaw = await res.json();
        return true;
      } catch {
        console.warn('[geo] 陆地掩膜未就绪,落水判定降级到行政区边界(抓不到沿海水域)');
        return false;
      }
    })();
  }
  return landPending;
}

/**
 * 给清洗用的几何:有陆地掩膜用陆地掩膜,没有降级到行政区边界。
 * 行政区边界作为降级路径只能抓「市域外」点,抓不到「岸线内却在水上」的点 —— 见上方注释。
 */
export function offshoreShapes(): NamedPolys[] | null {
  if (landRaw) return parseDistrictGeometry(landRaw);
  return allDistrictShapes();
}

/** 按当前区字典取匹配好的边界。数据还没到位返回 null —— 不返回空数组冒充「就是没有边界」 */
export function districtShapes(districtNames: string[]): DistrictShapeMatch | null {
  if (!raw) return null;
  if (lastMatch && lastNames === districtNames) return lastMatch;
  const match = matchDistrictShapes(raw, districtNames);
  lastNames = districtNames;
  lastMatch = match;
  return match;
}

/** 按字典下标取一个区的边界;没有(大鹏新区、未识别、名单没对上)返回 null */
export function districtShape(districtNames: string[], idx: number): DistrictShape | null {
  const shapes = districtShapes(districtNames)?.shapes ?? null;
  if (!shapes) return null;
  return shapes.find((s) => s.idx === idx) ?? null;
}