nearby.ts
2.99 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
/**
* 邻近参照点索引:只在 infer_nearby 打开时用到。
*
* 参照点来自两处 —— 本批里地址三项都读得出的行、以及缓存里已查过的坐标。
* 实测分布很密(42,806 行 / 3.3 万个唯一坐标,POI 级重复点成片),
* 所以「附近已有一个已知归属的点」通常成立;半径按字段分开定,见 targets.ts。
*/
/** 纬度方向每度米数(与主程序 cleanRules 同一口径) */
const M_PER_DEG_LAT = 111320;
function metersPerDegLng(latDeg: number): number {
return M_PER_DEG_LAT * Math.cos((latDeg * Math.PI) / 180);
}
export type RefPoint = {
/** 微度整数:既当缓存主键用,也免去逐行解析浮点文本 */
lng: number;
lat: number;
district: string;
street: string;
road: string;
};
export type NearHit = { meters: number; point: RefPoint };
/** 格边长(微度),0.003° 约 310m × 334m */
const CELL_MICRO = 3000;
export class NearbyIndex {
private readonly cells = new Map<string, RefPoint[]>();
constructor(points: Iterable<RefPoint>) {
for (const point of points) {
if (point.district === '' && point.street === '' && point.road === '') continue;
const key = `${Math.floor(point.lng / CELL_MICRO)}|${Math.floor(point.lat / CELL_MICRO)}`;
const bucket = this.cells.get(key);
if (bucket === undefined) this.cells.set(key, [point]);
else bucket.push(point);
}
}
/**
* 取半径内最近的合格参照点。
* `accept` 用来拒绝「参照点与本行已知的行政区不一致」这类答案 —— 邻近只回答
* 「这一带归哪个街道」,不能把案件记到隔壁区头上。
*/
nearest(lng: number, lat: number, maxMeters: number, accept: (p: RefPoint) => boolean): NearHit | null {
if (this.cells.size === 0 || maxMeters <= 0) return null;
const latDeg = Math.abs(lat / 1e6) + CELL_MICRO / 1e6;
// 每度经线的米数按「最不利」的那一头取:那里跨的格子最多,才不会漏搜
const mPerMicroLng = metersPerDegLng(latDeg) / 1e6;
const mPerMicroLat = M_PER_DEG_LAT / 1e6;
const spanLng = Math.ceil(maxMeters / (CELL_MICRO * mPerMicroLng)) + 1;
const spanLat = Math.ceil(maxMeters / (CELL_MICRO * mPerMicroLat)) + 1;
const gx = Math.floor(lng / CELL_MICRO);
const gy = Math.floor(lat / CELL_MICRO);
const atLng = metersPerDegLng(lat / 1e6) / 1e6;
let best: NearHit | null = null;
for (let dx = -spanLng; dx <= spanLng; dx += 1) {
for (let dy = -spanLat; dy <= spanLat; dy += 1) {
const bucket = this.cells.get(`${gx + dx}|${gy + dy}`);
if (bucket === undefined) continue;
for (const point of bucket) {
if (!accept(point)) continue;
const ex = (point.lng - lng) * atLng;
const ey = (point.lat - lat) * mPerMicroLat;
const meters = Math.sqrt(ex * ex + ey * ey);
if (meters <= maxMeters && (best === null || meters < best.meters)) best = { meters, point };
}
}
}
return best;
}
}