offshoreVerdict.ts 7.26 KB
/**
 * 「坐标落没落在陆域上」—— 清洗用来抓海上 / 域外点的核心判据(纯几何,无 IO)。
 *
 * 与「辖区归属」(纯地址文本,见 classifyOffshore 的 C 类互补说明)是两套互补口径:
 *   - 辖区归属管「地址写明外市」(东莞市 / 凤岗镇),坐标不参与;
 *   - 这里管「地址写的是深圳、坐标却不在任何陆域多边形内」——
 *     典型就是出险地址写着「大鹏新区大鹏街道」「南山区蛇口街道」(正确的深圳辖区名,C 类放行),
 *     坐标却飘到了海上。
 *
 * ⚠️ 掩膜必须是**真正的陆地(海岸线)多边形**,不是行政区边界:
 *    AMap 行政区边界(shenzhen.geojson)会把沿海区的**水域**也划进区界,导致
 *    「坐标在不在行政区多边形内」完全分不出海上点。所以调用方应优先喂陆地掩膜
 *    (shenzhen-land.geojson,Natural Earth 陆地裁剪),没有时才降级到行政区边界。
 *
 * @returns onLand 是否落在本陆域多边形内;distM 离最近陆界多少米
 *          (onLand 时为 0,offshore 时才算——那才是要交代给导入人的数)。
 */
import {
  boundsOf,
  distanceToBoundaryM,
  pointInPolygon,
  type LngLat,
  type NamedPolys,
  type ShapeBounds,
  type ShapePolygon,
} from './polygon';

export function offshoreVerdict(
  lng: number,
  lat: number,
  shapes: NamedPolys[],
): { onLand: boolean; distM: number; judged: boolean } {
  const { polys, ob } = prepShapes(shapes);
  // bbox 守卫:点落在掩膜覆盖区外时**无法判定** —— 既不判海上也不假装陆地,
  // 交回上层「不标不剔」(旧版在这里按陆地处理,会漏判南边 22.25 以下、或掩膜换成只盖深圳后的海域)。
  if (lng < ob.minLng || lng > ob.maxLng || lat < ob.minLat || lat > ob.maxLat) {
    return { onLand: true, distM: 0, judged: false };
  }
  for (const { p, b } of polys) {
    if (lng < b.minLng || lng > b.maxLng || lat < b.minLat || lat > b.maxLat) continue;
    if (pointInPolygon(lng, lat, p)) return { onLand: true, distM: 0, judged: true };
  }
  // 落在所有陆块之外:算到最近陆界的距离,交给导入人判断(码头 / 跨海大桥等合法点会靠距离分辨)
  const distM = distanceToBoundaryM(
    lng,
    lat,
    polys.map((x) => x.p),
  );
  return { onLand: false, distM, judged: true };
}

/**
 * 掩膜多边形按引用缓存:同一次导入 4 万多点共用同一份 `shapes`,逐点只做 bbox 预筛 +
 * 一次射线法,不会把每个点都拿去和 28 块陆块逐边比。整体包围框用来做「覆盖区外即按陆地」的守卫。
 */
interface Prepped {
  polys: Array<{ p: ShapePolygon; b: ShapeBounds }>;
  ob: ShapeBounds;
}
let _cachedShapes: NamedPolys[] | null = null;
let _cachedPrep: Prepped | null = null;

function prepShapes(shapes: NamedPolys[]): Prepped {
  if (_cachedShapes === shapes && _cachedPrep) return _cachedPrep;
  const polys: Prepped['polys'] = [];
  const ob: ShapeBounds = { minLng: Infinity, maxLng: -Infinity, minLat: Infinity, maxLat: -Infinity };
  for (const s of shapes) {
    for (const p of s.polys) {
      const b = boundsOf([p]);
      polys.push({ p, b });
      if (b.minLng < ob.minLng) ob.minLng = b.minLng;
      if (b.maxLng > ob.maxLng) ob.maxLng = b.maxLng;
      if (b.minLat < ob.minLat) ob.minLat = b.minLat;
      if (b.maxLat > ob.maxLat) ob.maxLat = b.maxLat;
    }
  }
  _cachedShapes = shapes;
  _cachedPrep = { polys, ob };
  return _cachedPrep;
}

/* ------------------------------- 几何解析(无 IO) ------------------------------- */

/**
 * 把区界 / 陆地掩膜 的 FeatureCollection 解析成 `NamedPolys[]`。
 *
 * 纯函数:不碰 fetch、不依赖字典匹配(那是主线程画区界时才有的事)。清洗跑在 Worker 里,
 * 只关心「这个点在不在这一堆多边形里」,所以走这条入口。
 * 解析几何这一段(`readFeatures` / `readPolygons` / `readRings`)与区界聚焦必须同一份 ——
 * 尤其 MultiPolygon 按块分组那一条,漏了就是整块判不进去。
 */
export function parseDistrictGeometry(raw: unknown): NamedPolys[] {
  const out: NamedPolys[] = [];
  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;
    out.push({ name, polys, bbox: boundsOf(polys) });
  }
  return out;
}

/**
 * 把 FeatureCollection 拆成「properties 平铺 + geometry」的记录数组。
 *
 * 单独导出是给**区界聚焦**(宿主主线程画区界)复用:那边除了几何还要 properties 里的
 * adcode / centroid 来定位标签,不能只拿 `NamedPolys`。解码规则必须与清洗侧同一份 ——
 * 尤其下面 `parseGeometryPolys` 的 MultiPolygon 按块分组那一条,漏了就是整块判不进去。
 */
export function parseGeoFeatures(raw: unknown): Array<Record<string, unknown>> {
  const fc = raw as { type?: string; features?: unknown };
  if (!fc || fc.type !== 'FeatureCollection' || !Array.isArray(fc.features)) {
    throw new Error('区界数据不是 FeatureCollection');
  }
  const out: Array<Record<string, unknown>> = [];
  for (const f of fc.features) {
    const feature = f as { properties?: Record<string, unknown>; geometry?: unknown };
    const props = feature.properties ?? {};
    out.push({ ...props, geometry: feature.geometry });
  }
  return out;
}

/**
 * Polygon 的 coordinates 是「环的数组」,MultiPolygon 是「多边形的数组」,这里统一成后者。
 *
 * ⚠️ 必须保留「块」的分组:龙岗区是 2 块,第二块就是大鹏半岛。把各块的环平铺成一条数组,
 * 第二块的外环会被当成「洞」,整块判不进去 —— 这个坑踩过一次,第一版探针因此把大鹏半岛的
 * 504 条案子全判成了域外。
 */
export function parseGeometryPolys(geometry: unknown): ShapePolygon[] {
  const g = geometry as { type?: string; coordinates?: unknown } | undefined;
  if (!g || (g.type !== 'Polygon' && g.type !== 'MultiPolygon') || !Array.isArray(g.coordinates)) {
    return [];
  }
  const polys: ShapePolygon[] = [];
  const lists: unknown[] = g.type === 'Polygon' ? [g.coordinates] : g.coordinates;
  for (const ringsRaw of lists) {
    const rings = readRings(ringsRaw);
    if (rings.length > 0) polys.push({ rings });
  }
  return polys;
}

/** 环必须至少 4 个位置(三角形闭合后就是 4 个),坐标必须是有限数;不闭合的补上首点 */
function readRings(ringsRaw: unknown): LngLat[][] {
  if (!Array.isArray(ringsRaw)) return [];
  const rings: LngLat[][] = [];
  for (const ringRaw of ringsRaw) {
    if (!Array.isArray(ringRaw)) continue;
    const pts: LngLat[] = [];
    for (const pos of ringRaw) {
      if (!Array.isArray(pos) || pos.length < 2) continue;
      const lng = Number(pos[0]);
      const lat = Number(pos[1]);
      if (!Number.isFinite(lng) || !Number.isFinite(lat)) continue;
      pts.push([lng, lat]);
    }
    if (pts.length < 3) continue;
    const head = pts[0];
    const tail = pts[pts.length - 1];
    if (head[0] !== tail[0] || head[1] !== tail[1]) pts.push([head[0], head[1]]);
    if (pts.length >= 4) rings.push(pts);
  }
  return rings;
}