projection.test.ts
3.4 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
/**
* 百度 GL 4.0 投影口径守卫。
*
* 2026-11-24 现场:自绘聚合点「拖一次往右跑一点、滚轮停下就消失、像叠了两个地图」。
* 根因是百度 GL 的缩放单位不是标准 256 瓦片墨卡托,自绘层却共用 APP_SCALE(256),
* 点位相对中心被放大约 1.675 倍。这里把这个口径的推导钉死,防止被改回 256。
*
* 权威依据(对着真实 911KB 脚本 + 浏览器实测,见 basemap.ts 注释):
* MercatorProjection.getZoomUnits(z) = 2^(18-z)
* → 每度像素 = (世界周长 / 2^18) × 2^z / 360
* → 等效 tileSize = 世界周长 / 2^18
*/
import { describe, expect, it } from 'vitest';
import { Frame, pxPerDegLng } from '@hm/map-overlay';
import { BAIDU_TILE_SIZE } from './BaiduBasemap';
/** 百度脚本里 getZoomUnits(z) 的实测规律 */
function baiduZoomUnits(zoom: number): number {
return Math.pow(2, 18 - zoom);
}
/** 真实墨卡托世界周长(米),与厂商无关 */
const WORLD_CIRCUMFERENCE = 40075016.68557849;
describe('百度投影口径', () => {
it('等效 tileSize = 世界周长 / 2^18,不是标准 256', () => {
expect(BAIDU_TILE_SIZE).toBeCloseTo(WORLD_CIRCUMFERENCE / Math.pow(2, 18), 9);
expect(BAIDU_TILE_SIZE).not.toBe(256);
// 比值:标准口径会把百度点位放大这么多倍
expect(256 / BAIDU_TILE_SIZE).toBeCloseTo(1.6746, 3);
});
it('每个缩放级别的每度像素都与 getZoomUnits 一致', () => {
// 百度真实:0.01° 的墨卡托差 = WORLD/360 × 0.01,除以每像素单位数
const mercPerDeg = WORLD_CIRCUMFERENCE / 360;
for (const zoom of [8, 9, 10, 11, 12, 13, 14, 15]) {
const formulaPxPerDeg = pxPerDegLng(zoom, BAIDU_TILE_SIZE);
const baiduPxPerDeg = mercPerDeg / baiduZoomUnits(zoom);
// Frame 的乘加口径与百度权威投影的差必须远小于 1px/度
expect(Math.abs(formulaPxPerDeg - baiduPxPerDeg)).toBeLessThan(0.02);
}
});
it('用 256 会显著偏高——锁住回归', () => {
const zoom = 11;
const wrong = pxPerDegLng(zoom, 256);
const right = pxPerDegLng(zoom, BAIDU_TILE_SIZE);
expect(wrong / right).toBeCloseTo(1.6746, 3);
});
it('Frame 的 latSlope 生效:同一墨卡托差在 slope<1 时屏幕位移更小', () => {
// 假地图:原点在画布中心,只问一次中心投影
const fakeMap = {
getSize: () => ({ width: 1000, height: 1000 }),
getCenter: () => ({ getLng: () => 114.06, getLat: () => 22.62 }),
getZoom: () => 11,
lngLatToContainer: () => ({ x: 500, y: 500 }),
};
const mercAt = (lat: number) =>
Math.log(Math.tan(Math.PI / 4 + (lat * Math.PI) / 360));
const target = mercAt(22.72); // 中心以北 0.1°
const plain = new Frame();
plain.set(fakeMap, 11, 114.06, 22.62, { tileSize: BAIDU_TILE_SIZE, referenceLat: 22.5 });
const corrected = new Frame();
corrected.set(fakeMap, 11, 114.06, 22.62, {
tileSize: BAIDU_TILE_SIZE,
referenceLat: 22.5,
latSlope: 0.99424,
});
// slope<1 → 同样的墨卡托差映射到更小的屏幕位移(y 更靠近原点)
expect(corrected.y(target)).toBeGreaterThan(plain.y(target));
// 位移之比恰好 = slope(原点 500,两者偏离量的比)
const plainOffset = 500 - plain.y(target);
const correctedOffset = 500 - corrected.y(target);
expect(correctedOffset / plainOffset).toBeCloseTo(0.99424, 4);
});
});