mapFrame.ts
14.6 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
/**
* 地图选点的独立文档(srcdoc iframe)。
*
* 为什么必须是独立文档:wujie 2.1.0 会 patch 子应用 iframe realm 的
* `Document.prototype.appendChild`,任何动态 `<script src>` 都走它的 `fetchAssets`
* (wujie/esm/entry.js:128)。百度地图 3.0 初始化时动态加载
* `qt=verify`、`heicha/mw/abclite`、`LuShu/BMapLib` 等脚本,这些域都没有 CORS 头,
* 在 wujie 沙箱里必挂;逐个关 SDK 插件开关是打地鼠,安全校验脚本关不掉。
* 源 temp/account/html/merchant/map.html 是独立 HTML 页面,脚本由浏览器原生加载,
* 所以这里用独立 iframe 文档还原它的运行环境,SDK 的发起方仍在 iframe 内。
*
* 为什么用注入回调而不是 postMessage:wujie 非降级模式把子应用 DOM 渲染在主文档
* shadowRoot,srcdoc iframe 的 parent 是主 window,而父组件的 message 监听被 wujie
* 绑在子应用执行 iframe window 上(common.js:82),两边收不到——表现为「地图下有地址,
* 点确定仍提示请选择地址」。改成父组件 onLoad 时把函数引用挂到 iframe window 上,
* iframe 直接调用,同源引用传递,绕开事件路由。
*
* 交互口径逐字对应源 map.html:
* - searchInput + 搜索按钮 → getPoint(地址 → 坐标) L114-119 / L306-326
* - 点击地图 → setLocation → getLocation(坐标 → 地址) L141-146 / L186-198 / L272-303
* - 初始坐标落 marker 并反查;无坐标时 Geolocation 落点 L147-165
* - 详细地址由反查填入,用户可改,以最后一次 change 为准 L76 / L129-135 / L283-284
* - invoke 方法名、'全国' 范围参数、DEFAULT_CENTER 均同源 L144 / L315-326
*/
export interface MapFrameInitial {
lat?: string;
lng?: string;
merchantAddress?: string;
}
export interface MapFrameValue {
lat: number;
lng: number;
merchantAddress: string;
provinceName: string;
cityName: string;
}
export type MapFrameEvent =
| { source: 'uj-map-frame'; type: 'ready' }
| { source: 'uj-map-frame'; type: 'change'; payload: MapFrameValue }
| { source: 'uj-map-frame'; type: 'warn'; payload: { message: string } }
| { source: 'uj-map-frame'; type: 'error'; payload: { message: string } };
export function isMapFrameEvent(value: unknown): value is MapFrameEvent {
if (!value || typeof value !== 'object') return false;
const event = value as Partial<MapFrameEvent>;
return (
event.source === 'uj-map-frame' &&
(event.type === 'ready' ||
event.type === 'change' ||
event.type === 'warn' ||
event.type === 'error')
);
}
/**
* apiUrl 来自配置中心 map-api-js(父页面 fetch 拿,配置中心有 CORS 头,这一步本来就通)。
* 源 js/glsk-mapapi-sdk.js 把 apiUrl 作为 <script src> 注入,这里一样。
*/
export function buildMapFrameHtml(apiUrl: string, initial: MapFrameInitial): string {
// 所有外部输入以 JSON 字面量注入,杜绝字符串拼接进脚本造成的注入/截断。
const sdkUrl = JSON.stringify(apiUrl);
const seed = JSON.stringify(initial);
return `<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style>
:root {
--primary: #2b5ce6;
--primary-hover: #4b75ea;
--primary-soft: #eef3ff;
--surface: #ffffff;
--surface-2: #f8fafc;
--border: #e6ebf2;
--border-strong: #d6dee9;
--text-1: #1d2533;
--text-2: #4a5568;
--text-3: #8a94a6;
--success: #16a34a;
--success-soft: #e9f7ef;
--error: #e5484d;
--error-soft: #fdedee;
--ease: cubic-bezier(0.2, 0, 0, 1);
}
* { box-sizing: border-box; }
html, body { margin: 0; padding: 0; }
body {
margin: 0;
overflow: hidden;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
color: var(--text-1);
background: var(--surface);
-webkit-font-smoothing: antialiased;
}
[hidden] { display: none !important; }
html, body { height: 100%; }
/* 地图即画布:canvas 铺满整个 iframe,搜索/地址以浮层卡片压在地图上,
不再纵向堆「搜索行 + 地图 + 地址行」三段。 */
.map-frame { position: relative; height: 100%; overflow: hidden; background: var(--surface-2); }
#container { position: absolute; inset: 0; width: 100%; height: 100%; }
.map-frame__search {
position: absolute; top: 12px; left: 12px; z-index: 10;
display: flex; gap: 8px;
width: min(380px, calc(100% - 24px));
padding: 8px;
border: 1px solid var(--border); border-radius: 10px;
background: rgba(255, 255, 255, 0.94);
box-shadow: 0 4px 16px rgba(29,37,51,.12);
backdrop-filter: blur(4px);
}
.map-frame__field { position: relative; flex: 1; min-width: 0; }
.map-frame__field svg {
position: absolute; left: 12px; top: 50%; transform: translateY(-50%);
width: 16px; height: 16px; color: var(--text-3); pointer-events: none;
}
.map-frame__search input,
.map-frame__address input {
width: 100%; height: 34px;
border: 1px solid var(--border);
border-radius: 6px;
background: var(--surface);
font-size: 14px;
color: var(--text-1);
transition: border-color 200ms var(--ease), box-shadow 200ms var(--ease);
outline: none;
}
.map-frame__search input { padding: 0 12px 0 36px; }
.map-frame__search input::placeholder,
.map-frame__address input::placeholder { color: var(--text-3); }
.map-frame__search input:hover,
.map-frame__address input:hover { border-color: var(--border-strong); }
.map-frame__search input:focus,
.map-frame__address input:focus {
border-color: var(--primary);
box-shadow: 0 0 0 3px var(--primary-soft);
}
.map-frame__search button {
flex: none;
height: 34px; padding: 0 16px;
border: 0; border-radius: 6px;
background: var(--primary); color: #fff;
font-size: 14px; font-weight: 600; cursor: pointer;
transition: background 150ms var(--ease), transform 150ms var(--ease);
}
.map-frame__search button:hover { background: var(--primary-hover); transform: translateY(-1px); }
.map-frame__search button:active { transform: translateY(0); }
.map-frame__loading {
position: absolute; inset: 0; z-index: 5;
display: flex; align-items: center; justify-content: center; gap: 10px;
background: var(--surface-2);
color: var(--text-3); font-size: 13px;
}
.map-frame__spinner {
width: 16px; height: 16px;
border: 2px solid var(--border-strong);
border-top-color: var(--primary);
border-radius: 50%;
animation: map-spin 700ms linear infinite;
}
@keyframes map-spin { to { transform: rotate(360deg); } }
/* 底部浮条:左=可编辑详细地址,右=已选坐标;替代原来的地址行 + 绿色状态块两层 */
.map-frame__address {
position: absolute; left: 12px; right: 12px; bottom: 12px; z-index: 10;
display: flex; align-items: center; gap: 8px;
padding: 8px;
border: 1px solid var(--border); border-radius: 10px;
background: rgba(255, 255, 255, 0.94);
box-shadow: 0 4px 16px rgba(29,37,51,.12);
backdrop-filter: blur(4px);
}
.map-frame__address input { flex: 1; min-width: 0; padding: 0 12px; }
.map-frame__coords {
flex: none;
padding: 6px 10px;
border-radius: 6px;
background: var(--success-soft); color: var(--success);
font-size: 12px; line-height: 1.4;
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.map-frame__coords .is-muted { color: var(--text-3); }
.map-frame__error {
position: absolute; top: 58px; left: 12px; right: 12px; z-index: 20;
padding: 10px 12px;
border: 1px solid #f8cfd1; border-radius: 8px;
background: var(--error-soft); color: var(--error);
font-size: 13px; line-height: 1.5;
box-shadow: 0 4px 16px rgba(29,37,51,.12);
}
</style>
</head>
<body>
<div class="map-frame">
<div id="container"></div>
<div id="mapLoading" class="map-frame__loading"><span class="map-frame__spinner"></span>地图加载中…</div>
<div class="map-frame__search">
<div class="map-frame__field">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<circle cx="11" cy="11" r="7"></circle><path d="m20 20-3.5-3.5"></path>
</svg>
<input id="searchInput" placeholder="搜索地点,或直接点击地图选点" />
</div>
<button id="searchBtn" type="button">搜索</button>
</div>
<div class="map-frame__address">
<input id="addressInput" placeholder="详细地址(地图选点后自动填入,可修改)" />
<span id="mapCoords" class="map-frame__coords" hidden></span>
</div>
</div>
<script>
(function () {
var source = 'uj-map-frame';
var seed = ${seed};
var DEFAULT_CENTER = { lng: 113.736716, lat: 23.069466 };
var api = null;
var map = null;
var marker = null;
var point = null;
var current = null;
var pending = [];
// 父组件在 iframe onLoad 时注入 __ujMapCallback;SDK 可能先于 onLoad 回调,故先缓存。
function post(type, payload) {
var msg = { source: source, type: type };
if (payload !== undefined) msg.payload = payload;
if (typeof window.__ujMapCallback === 'function') window.__ujMapCallback(msg);
else pending.push(msg);
}
window.__ujMapFlush = function () {
if (typeof window.__ujMapCallback !== 'function') return;
for (var i = 0; i < pending.length; i++) window.__ujMapCallback(pending[i]);
pending = [];
};
function fail(message) { post('error', { message: message }); }
function showError(message) {
var box = document.createElement('div');
box.className = 'map-frame__error';
box.textContent = message;
var frame = document.querySelector('.map-frame');
frame.insertBefore(box, frame.firstChild);
document.getElementById('mapLoading').hidden = true;
}
function pointOf(p) { return api.invoke('Point', p.lng, p.lat); }
function placeMarker(p) {
var xy = pointOf(p);
if (marker) api.invoke('removeOverlay', marker);
marker = api.invoke('Marker', xy);
api.invoke('markerEnableDragging');
api.invoke('addOverlay', marker);
api.invoke('panTo', xy);
}
function reverseGeocode(p) {
api.invoke('getLocation', pointOf(p), function (res) {
if (!res) return;
var pois = res.surroundingPois || [];
var address = (pois.length && pois[0] && pois[0].address) || res.address || '';
var components = res.addressComponents || {};
current = {
lat: (res.point && res.point.lat) || p.lat,
lng: (res.point && res.point.lng) || p.lng,
merchantAddress: address,
provinceName: components.province || '',
cityName: components.city || components.district || ''
};
if (address) document.getElementById('addressInput').value = address;
var coords = document.getElementById('mapCoords');
coords.innerHTML =
'<span class="is-muted">坐标</span> ' + current.lng.toFixed(6) + ', ' + current.lat.toFixed(6);
coords.hidden = false;
post('change', current);
});
}
function setLocation(e) {
if (!e || !e.point) return;
point = { lng: e.point.lng, lat: e.point.lat };
placeMarker(point);
reverseGeocode(point);
}
function search() {
if (!api || !map) return;
var keyword = document.getElementById('searchInput').value.trim();
if (!keyword) return;
api.invoke('getPoint', keyword, function (res) {
if (!res || !res.lng || !res.lat) {
post('warn', { message: '未查询到当前地址,请尝试更换搜索关键字' });
return;
}
point = { lng: res.lng, lat: res.lat };
placeMarker(point);
reverseGeocode(point);
}, '全国');
}
document.getElementById('searchBtn').addEventListener('click', search);
document.getElementById('searchInput').addEventListener('keydown', function (e) {
if (e.key === 'Enter') search();
});
document.getElementById('addressInput').addEventListener('input', function (e) {
if (current) {
current.merchantAddress = e.target.value;
post('change', current);
}
});
function start(apiHandle) {
api = apiHandle;
// 源 map.html:141-146:invoke('Map', 'container') 返回 Promise。
Promise.resolve(api.invoke('Map', 'container')).then(function (mapInstance) {
map = mapInstance;
document.getElementById('mapLoading').hidden = true;
api.invoke('centerAndZoom', pointOf(DEFAULT_CENTER), 15);
api.invoke('mapAddEventListener', 'click', setLocation);
if (map.enableScrollWheelZoom) map.enableScrollWheelZoom(true);
if (seed.lat && seed.lng) {
point = { lng: Number(seed.lng), lat: Number(seed.lat) };
document.getElementById('addressInput').value = seed.merchantAddress || '';
placeMarker(point);
reverseGeocode(point);
} else {
api.invoke('Geolocation', function (res) {
if (!res || !res.longitude || !res.latitude) return;
point = { lng: res.longitude, lat: res.latitude };
placeMarker(point);
reverseGeocode(point);
});
}
post('ready');
}).catch(function (error) {
var message = error && error.message ? error.message : String(error);
showError(message);
fail(message);
});
}
// 与源 glsk-mapapi-sdk.js 等价:GlMapApi 构造回调拿到 loader,invoke 代理到实例方法。
function install() {
var ctor = window.$GlMapApi;
if (typeof ctor !== 'function') {
showError('地图 SDK 全局对象不可用');
fail('地图 SDK 全局对象不可用');
return;
}
var instance = null;
var handle = {
invoke: function (method) {
var fn = instance && instance[method];
if (typeof fn !== 'function') throw new Error('地图方法 ' + method + ' 不可用');
return fn.apply(instance, Array.prototype.slice.call(arguments, 1));
}
};
try {
// hasLushu:false 关掉百度路书插件(源 SDK 构造默认 true,会拉无 CORS 头的 LuShu/BMapLib)。
instance = new ctor({ env: 3, version: 3, hasLushu: false }, function () {
start(handle);
});
} catch (error) {
var message = error && error.message ? error.message : String(error);
showError(message);
fail(message);
}
}
var script = document.createElement('script');
script.src = ${sdkUrl};
script.async = true;
script.onerror = function () {
showError('地图脚本加载失败,请检查网络后重试');
fail('地图脚本加载失败,请检查网络后重试');
};
script.onload = install;
document.head.appendChild(script);
}());
</script>
</body>
</html>`;
}