tuqin
3 天以前 abfe3ffe5f6d161f2a6466c8bdbcbc17de1e64b6
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
<!-- 考勤地点地图选择器:百度地图展示,对外统一输出 WGS84 坐标 -->
<script lang="ts" setup>
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
 
import { Alert, Button, Input, InputNumber, Spin, message } from 'ant-design-vue';
 
import { loadBaiduMapSdk } from '#/components/map';
 
/** 对外输出:WGS84 坐标 + 反查到的地址/地点名 */
interface LocationSelection {
  address?: string;
  latitude: number;
  locationName?: string;
  longitude: number;
}
 
interface Props {
  disabled?: boolean;
  latitude?: number;
  longitude?: number;
  radiusMeters?: number;
}
 
const props = withDefaults(defineProps<Props>(), {
  disabled: false,
  latitude: undefined,
  longitude: undefined,
  radiusMeters: 10,
});
 
const emit = defineEmits<{
  select: [location: LocationSelection];
}>();
 
/** 默认中心点:新疆乌鲁木齐,未配置坐标时使用 */
const DEFAULT_CENTER: [number, number] = [87.625, 43.835];
const PI = Math.PI;
const X_PI = (PI * 3000) / 180;
const EARTH_SEMI_MAJOR_AXIS = 6_378_245;
const EARTH_ECCENTRICITY_SQUARED = 0.006_693_421_622_965_943;
 
/* eslint-disable @typescript-eslint/no-explicit-any */
type AnyMap = any;
 
const mapContainer = ref<HTMLElement>();
const loading = ref(false);
const searchKeyword = ref('');
const selectedAddress = ref('');
 
/**
 * 手工填写模式。
 *
 * 触发场景:百度地图 SDK 拿不到(企业网络拦截 api.map.baidu.com、
 * 浏览器插件拦截、ak 域名白名单未放开等)。
 * 此前这种情况会直接抛 "Cannot read properties of null (reading 'Map')" 或
 * "百度地图 SDK 加载失败",用户连考勤规则都存不了。
 * 现在改为:地图不可用时自动切换到手工输入经纬度,保证业务不中断。
 */
const manualMode = ref(false);
const manualName = ref('');
const manualLongitude = ref<number>();
const manualLatitude = ref<number>();
 
let map: AnyMap;
let marker: AnyMap;
let rangeCircle: AnyMap;
let geocoder: AnyMap;
/**
 * 组件是否已卸载。
 *
 * 百度地图 SDK 是异步加载的(loadBaiduMapSdk 内部创建 script 标签)。
 * 用户打开定位后如果很快点「确认」或「取消」,弹窗关闭 → 本组件卸载 → 地图容器从 DOM 移除,
 * 但加载流程仍在 await 中继续,等 SDK 就绪后会执行 new BMapGL.Map(mapContainer.value),
 * 此时 mapContainer 已是 null,百度地图内部会抛
 * "Cannot read properties of null (reading 'Map')"。
 * 用这个标志位让异步流程在卸载后立即退出。
 */
let disposed = false;
 
const baiduMapKey = String(import.meta.env.VITE_BAIDU_MAP_KEY ?? '').trim();
const hasMapConfig = computed(() => Boolean(baiduMapKey));
 
function outOfChina(longitude: number, latitude: number) {
  return (
    longitude < 72.004 ||
    longitude > 137.8347 ||
    latitude < 0.8293 ||
    latitude > 55.8271
  );
}
 
function transformLatitude(longitude: number, latitude: number) {
  let result =
    -100 +
    2 * longitude +
    3 * latitude +
    0.2 * latitude * latitude +
    0.1 * longitude * latitude +
    0.2 * Math.sqrt(Math.abs(longitude));
  result +=
    ((20 * Math.sin(6 * longitude * PI) + 20 * Math.sin(2 * longitude * PI)) * 2) / 3;
  result +=
    ((20 * Math.sin(latitude * PI) + 40 * Math.sin((latitude / 3) * PI)) * 2) / 3;
  result +=
    ((160 * Math.sin((latitude / 12) * PI) +
      320 * Math.sin((latitude * PI) / 30)) *
      2) /
    3;
  return result;
}
 
function transformLongitude(longitude: number, latitude: number) {
  let result =
    300 +
    longitude +
    2 * latitude +
    0.1 * longitude * longitude +
    0.1 * longitude * latitude +
    0.1 * Math.sqrt(Math.abs(longitude));
  result +=
    ((20 * Math.sin(6 * longitude * PI) + 20 * Math.sin(2 * longitude * PI)) * 2) / 3;
  result +=
    ((20 * Math.sin(longitude * PI) + 40 * Math.sin((longitude / 3) * PI)) * 2) / 3;
  result +=
    ((150 * Math.sin((longitude / 12) * PI) +
      300 * Math.sin((longitude / 30) * PI)) *
      2) /
    3;
  return result;
}
 
/** WGS84 → GCJ02 */
function wgs84ToGcj02(longitude: number, latitude: number): [number, number] {
  if (outOfChina(longitude, latitude)) {
    return [longitude, latitude];
  }
  let deltaLatitude = transformLatitude(longitude - 105, latitude - 35);
  let deltaLongitude = transformLongitude(longitude - 105, latitude - 35);
  const radianLatitude = (latitude / 180) * PI;
  let magic = Math.sin(radianLatitude);
  magic = 1 - EARTH_ECCENTRICITY_SQUARED * magic * magic;
  const sqrtMagic = Math.sqrt(magic);
  deltaLatitude =
    (deltaLatitude * 180) /
    (((EARTH_SEMI_MAJOR_AXIS * (1 - EARTH_ECCENTRICITY_SQUARED)) /
      (magic * sqrtMagic)) *
      PI);
  deltaLongitude =
    (deltaLongitude * 180) /
    ((EARTH_SEMI_MAJOR_AXIS / sqrtMagic) * Math.cos(radianLatitude) * PI);
  return [longitude + deltaLongitude, latitude + deltaLatitude];
}
 
/** GCJ02 → WGS84,迭代逼近,误差可控制在 0.5 米内 */
function gcj02ToWgs84(longitude: number, latitude: number): [number, number] {
  if (outOfChina(longitude, latitude)) {
    return [longitude, latitude];
  }
  let wgsLongitude = longitude;
  let wgsLatitude = latitude;
  for (let index = 0; index < 5; index++) {
    const [gcjLongitude, gcjLatitude] = wgs84ToGcj02(wgsLongitude, wgsLatitude);
    wgsLongitude += longitude - gcjLongitude;
    wgsLatitude += latitude - gcjLatitude;
  }
  return [wgsLongitude, wgsLatitude];
}
 
/** GCJ02 → BD09 */
function gcj02ToBd09(longitude: number, latitude: number): [number, number] {
  const z =
    Math.sqrt(longitude * longitude + latitude * latitude) +
    0.000_02 * Math.sin(latitude * X_PI);
  const theta =
    Math.atan2(latitude, longitude) + 0.000_003 * Math.cos(longitude * X_PI);
  return [z * Math.cos(theta) + 0.0065, z * Math.sin(theta) + 0.006];
}
 
/** BD09 → GCJ02 */
function bd09ToGcj02(longitude: number, latitude: number): [number, number] {
  const x = longitude - 0.0065;
  const y = latitude - 0.006;
  const z = Math.sqrt(x * x + y * y) - 0.000_02 * Math.sin(y * X_PI);
  const theta = Math.atan2(y, x) - 0.000_003 * Math.cos(x * X_PI);
  return [z * Math.cos(theta), z * Math.sin(theta)];
}
 
function wgs84ToBd09(longitude: number, latitude: number): [number, number] {
  return gcj02ToBd09(...wgs84ToGcj02(longitude, latitude));
}
 
function bd09ToWgs84(longitude: number, latitude: number): [number, number] {
  return gcj02ToWgs84(...bd09ToGcj02(longitude, latitude));
}
 
function updateOverlay(
  longitude: number,
  latitude: number,
  centerMap = false,
) {
  if (!map || !window.BMapGL) {
    return;
  }
  const point = new window.BMapGL.Point(longitude, latitude);
  if (!marker) {
    marker = new window.BMapGL.Marker(point);
    map.addOverlay(marker);
  } else {
    marker.setPosition(point);
  }
  if (!rangeCircle) {
    rangeCircle = new window.BMapGL.Circle(point, props.radiusMeters, {
      fillColor: '#1677ff',
      fillOpacity: 0.16,
      strokeColor: '#1677ff',
      strokeOpacity: 0.8,
      strokeWeight: 2,
    });
    map.addOverlay(rangeCircle);
  } else {
    rangeCircle.setCenter(point);
    rangeCircle.setRadius(props.radiusMeters);
  }
  if (centerMap) {
    map.centerAndZoom(point, 19);
  }
}
 
function reverseGeocode(longitude: number, latitude: number) {
  return new Promise<{ address?: string; name?: string }>((resolve) => {
    if (!geocoder) {
      resolve({});
      return;
    }
    geocoder.getLocation(
      new window.BMapGL.Point(longitude, latitude),
      (result: any) => {
        const components = result?.addressComponents ?? {};
        const nearestPoi = result?.surroundingPois?.[0]?.title;
        resolve({
          address: result?.address,
          name:
            nearestPoi ||
            components.street ||
            components.district ||
            components.city,
        });
      },
    );
  });
}
 
/** 地图坐标(BD09)落点后,回传 WGS84 给表单 */
async function selectBaiduLocation(
  longitude: number,
  latitude: number,
  centerMap = true,
) {
  updateOverlay(longitude, latitude, centerMap);
  const [wgsLongitude, wgsLatitude] = bd09ToWgs84(longitude, latitude);
  const location = await reverseGeocode(longitude, latitude);
  selectedAddress.value = location.address ?? '';
  emit('select', {
    address: location.address,
    latitude: Number(wgsLatitude.toFixed(7)),
    locationName: location.name,
    longitude: Number(wgsLongitude.toFixed(7)),
  });
}
 
/**
 * 切换到手工填写模式。
 *
 * 百度地图依赖第三方 CDN(api.map.baidu.com),在内网、被防火墙拦截、
 * 浏览器插件拦截、ak 域名白名单未放开的场景下都拿不到 SDK。
 * 此时必须降级,否则用户连考勤规则都存不了(后端要求定位开启时地点名称+经纬度必填)。
 */
function switchToManual(reason: string) {
  if (disposed) {
    return;
  }
  manualMode.value = true;
  loading.value = false;
  if (!manualName.value) {
    manualName.value = selectedAddress.value || '';
  }
  if (!Number.isFinite(manualLongitude.value) && Number.isFinite(props.longitude)) {
    manualLongitude.value = Number(props.longitude);
  }
  if (!Number.isFinite(manualLatitude.value) && Number.isFinite(props.latitude)) {
    manualLatitude.value = Number(props.latitude);
  }
  message.warning(`${reason},已切换为手工填写坐标`);
}
 
/** 手工填写坐标后回填表单 */
function applyManual() {
  const longitude = Number(manualLongitude.value);
  const latitude = Number(manualLatitude.value);
  if (!Number.isFinite(longitude) || !Number.isFinite(latitude)) {
    message.warning('请填写经度和纬度');
    return;
  }
  if (longitude < -180 || longitude > 180) {
    message.warning('经度应在 -180 ~ 180 之间');
    return;
  }
  if (latitude < -90 || latitude > 90) {
    message.warning('纬度应在 -90 ~ 90 之间');
    return;
  }
  const name = manualName.value.trim();
  emit('select', {
    address: name || undefined,
    latitude: Number(latitude.toFixed(7)),
    locationName: name || undefined,
    longitude: Number(longitude.toFixed(7)),
  });
  message.success('坐标已应用');
}
 
async function handleSearch() {
  const keyword = searchKeyword.value.trim();
  if (!keyword || !geocoder) {
    return;
  }
  loading.value = true;
  try {
    const point = await new Promise<any>((resolve, reject) => {
      geocoder.getPoint(keyword, (result: any) => {
        result
          ? resolve(result)
          : reject(
              new Error('没有搜索到该地址,请输入更完整的省市区和地点名称'),
            );
      });
    });
    await selectBaiduLocation(point.lng, point.lat);
  } catch (error: any) {
    message.warning(error?.message || '地址搜索失败');
  } finally {
    loading.value = false;
  }
}
 
async function initializeMap() {
  if (!hasMapConfig.value || !mapContainer.value) {
    return;
  }
  loading.value = true;
  try {
    await loadBaiduMapSdk(15_000);
    // 卸载后立即退出:此时地图容器已从 DOM 移除,继续初始化会抛 null.Map
    if (disposed || !mapContainer.value) {
      return;
    }
    await nextTick();
    if (disposed || !mapContainer.value) {
      return;
    }
    // SDK 回调触发但 BMapGL 未挂载(常见于 ak 无效 / 域名未授权 / 被网络拦截)
    if (!window.BMapGL) {
      switchToManual('地图组件未就绪,可手工填写坐标');
      return;
    }
    const hasCoordinates =
      Number.isFinite(props.longitude) && Number.isFinite(props.latitude);
    const center = hasCoordinates
      ? wgs84ToBd09(Number(props.longitude), Number(props.latitude))
      : DEFAULT_CENTER;
    map = new window.BMapGL.Map(mapContainer.value);
    if (disposed) {
      // 初始化过程中被卸载,直接销毁,避免残留实例
      map?.destroy?.();
      map = undefined;
      return;
    }
    map.centerAndZoom(
      new window.BMapGL.Point(center[0], center[1]),
      hasCoordinates ? 19 : 12,
    );
    map.enableScrollWheelZoom(true);
    map.addControl(new window.BMapGL.ZoomControl());
    map.addControl(new window.BMapGL.ScaleControl());
    geocoder = new window.BMapGL.Geocoder();
    map.addEventListener('click', (event: any) => {
      if (!props.disabled) {
        void selectBaiduLocation(event.latlng.lng, event.latlng.lat, false);
      }
    });
    if (hasCoordinates) {
      updateOverlay(center[0], center[1]);
      const location = await reverseGeocode(center[0], center[1]);
      selectedAddress.value = location.address ?? '';
    }
  } catch (error: any) {
    // 地图不可用(网络拦截 / ak 未授权 / 超时)时降级为手工填写,不能阻塞业务
    switchToManual(error?.message || '地图加载失败');
  } finally {
    loading.value = false;
  }
}
 
watch(
  () => [props.longitude, props.latitude] as const,
  ([longitude, latitude]) => {
    if (
      !map ||
      !Number.isFinite(longitude) ||
      !Number.isFinite(latitude)
    ) {
      return;
    }
    const point = wgs84ToBd09(Number(longitude), Number(latitude));
    updateOverlay(point[0], point[1]);
  },
);
 
watch(
  () => props.radiusMeters,
  (radius) => {
    if (Number.isFinite(radius)) {
      rangeCircle?.setRadius(Number(radius));
    }
  },
);
 
onMounted(initializeMap);
 
onBeforeUnmount(() => {
  // 先置标志位,让还在 await 中的 initializeMap 立即退出
  disposed = true;
  try {
    map?.clearOverlays?.();
    map?.destroy?.();
  } catch (error) {
    // 地图实例若处于半初始化状态,destroy 内部可能报错,这里吞掉避免影响弹窗关闭
    console.warn('[LocationMapPicker] 销毁地图实例失败', error);
  }
  map = undefined;
  marker = undefined;
  rangeCircle = undefined;
  geocoder = undefined;
});
</script>
 
<template>
  <Alert
    v-if="!hasMapConfig"
    type="warning"
    show-icon
    message="百度地图尚未配置"
    description="未配置 VITE_BAIDU_MAP_KEY,请手工填写打卡地点的经纬度。"
  />
  <template v-else>
    <!-- 地图不可用时的手工填写模式,保证业务不被第三方 CDN 卡住 -->
    <template v-if="manualMode">
      <Alert
        type="info"
        show-icon
        class="mb-2"
        message="地图不可用,已切换为手工填写坐标"
        description="如长期无法加载地图,请检查服务器/浏览器是否允许访问 api.map.baidu.com,或联系管理员确认百度地图 Key 的域名白名单。"
      />
      <div class="grid grid-cols-3 gap-2">
        <Input
          v-model:value="manualName"
          :disabled="disabled"
          placeholder="打卡地点名称,如:厂区大门"
        />
        <InputNumber
          v-model:value="manualLongitude"
          :disabled="disabled"
          :precision="7"
          :step="0.0001"
          class="w-full"
          placeholder="经度,如 87.616848"
        />
        <InputNumber
          v-model:value="manualLatitude"
          :disabled="disabled"
          :precision="7"
          :step="0.0001"
          class="w-full"
          placeholder="纬度,如 43.825592"
        />
      </div>
      <div class="mt-2 flex items-center justify-between">
        <span class="text-xs text-gray-500">
          坐标须为 WGS84(GPS 原始坐标),允许范围 {{ radiusMeters }} 米
        </span>
        <Button v-if="!disabled" type="primary" @click="applyManual">
          应用坐标
        </Button>
      </div>
    </template>
    <Spin v-else :spinning="loading">
      <div v-if="!disabled" class="mb-2 flex gap-2">
        <Input
          v-model:value="searchKeyword"
          allow-clear
          placeholder="输入省、市、区和具体地点,例如:乌鲁木齐市厂区"
          @press-enter="handleSearch"
        />
        <Button :loading="loading" @click="handleSearch">搜索地址</Button>
      </div>
      <div
        ref="mapContainer"
        class="h-[360px] w-full overflow-hidden rounded border border-gray-200"
      ></div>
      <div
        class="mt-2 flex flex-wrap justify-between gap-2 text-xs text-gray-500"
      >
        <span>
          {{
            disabled
              ? '打卡位置及允许范围'
              : '点击地图选择打卡中心点;蓝色圆圈表示允许打卡范围'
          }}
        </span>
        <span v-if="selectedAddress">{{ selectedAddress }}</span>
      </div>
    </Spin>
  </template>
</template>