WebApp【公共组件库】@前端(For Git Submodule)
Tevin
2025-04-09 e9799a5b4b9f221447cba49e8fbf7bea6b6c0c42
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
/**
 * CBaiduMap - 百度地图组件
 * @author chensi
 */
 
<template>
    <view class="c-baidu-map">
        <map
            id="map"
            class="map"
            :latitude="mapLatitude"
            :longitude="mapLongitude"
            :markers="markers"
            :scale="mapScale"
            show-location
            enable-rotate
            enable-satellite
            enable-traffic
            enable-3D
            enable-building
            @tap="evt => handleMapTap(evt)"
            @markertap="evt => handleMarkerTap(evt)"
            @regionchange="evt => handleRegionChange(evt)"
        ></map>
        <view class="map-controls">
            <view class="map-controls-top">
                <AtButton
                    type="primary"
                    size="small"
                    :onClick="evt => handleChooseLocation(evt)"
                >选择位置</AtButton>
                <AtButton
                    type="primary"
                    size="small"
                    :onClick="evt => handleGetLocation(evt)"
                >获取当前位置</AtButton>
            </view>
            <view class="map-controls-bottom">
                <AtButton
                    type="primary"
                    size="small"
                    class="btn-info"
                    :onClick="evt => handleSaveLocation(evt)"
                >保存</AtButton>
            </view>
        </view>
    </view>
</template>
 
<script>
import Taro from '@tarojs/taro';
import { AtButton } from 'taro-ui-vue';
import { BAIDU_MAP, BMapWX } from './index';
import './cBaiduMap.scss';
 
export default {
    name: 'CBaiduMap',
    components: {
        AtButton,
    },
    props: {
        latitude: {
            type: Number,
            default: 39.90886,
        },
        longitude: {
            type: Number,
            default: 116.39739,
        },
    },
    data() {
        return {
            // 地图上下文
            mapCtx: null,
            // 地图是否准备就绪
            isMapReady: false,
            // 当前位置
            currentLocation: null,
            // 标记点id
            selectedMarkerId: 0,
            // 标记点列表
            markers: [],
            // 本地维护的坐标
            localLatitude: this.latitude,
            localLongitude: this.longitude,
            // 地图坐标
            mapLatitude: this.latitude,
            mapLongitude: this.longitude,
            // 地图缩放级别
            mapScale: 14,
            // 是否由chooseLocation触发移动
            isFromChooseLocation: false,
        };
    },
    watch: {
        latitude: {
            handler(newVal) {
                if (newVal && this.longitude && this.isValidLatitude(newVal)) {
                    // 只在回显时更新本地坐标
                    this.localLatitude = newVal;
                    this.moveToLocation(newVal, this.longitude);
                }
            },
            immediate: false,
        },
        longitude: {
            handler(newVal) {
                if (newVal && this.latitude && this.isValidLongitude(newVal)) {
                    // 只在回显时更新本地坐标
                    this.localLongitude = newVal;
                    this.moveToLocation(this.latitude, newVal);
                }
            },
            immediate: false,
        },
    },
    mounted() {
        // 初始化地图
        this.initMap();
        // 设置一个延时,确保地图组件已完全加载
        setTimeout(() => {
            // 使用默认值处理可能的undefined或null
            const latitude = this.latitude || 39.90886;
            const longitude = this.longitude || 116.39739;
            // 确保坐标有效
            if (this.isValidLatitude(latitude) && this.isValidLongitude(longitude)) {
                this.localLatitude = latitude;
                this.localLongitude = longitude;
                this.initLocation();
            }
        }, 800);
    },
    methods: {
        // 验证纬度是否有效
        isValidLatitude(lat) {
            return lat >= -90 && lat <= 90;
        },
 
        // 验证经度是否有效
        isValidLongitude(lng) {
            return lng >= -180 && lng <= 180;
        },
 
        // 初始化地图
        initMap() {
            try {
                // 初始化地图上下文
                this.mapCtx = Taro.createMapContext('map', this);
                // 检查地图是否准备就绪
                this.checkMapReady();
            } catch (error) {
                console.error('初始化地图失败:', error);
            }
        },
 
        // 检查地图是否准备就绪
        checkMapReady() {
            if (this.mapCtx) {
                this.mapCtx.getCenterLocation({
                    success: res => {
                        this.isMapReady = true;
                    },
                    fail: err => {
                        console.error('获取地图中心点失败:', err);
                    },
                });
            }
        },
 
        // 地图区域改变事件
        async handleRegionChange(evt) {
            // 如果是由chooseLocation触发的移动,则不处理
            if (this.isFromChooseLocation) {
                return;
            }
            if (!evt.detail || !evt.detail.centerLocation) {
                return;
            }
            const { latitude, longitude } = evt.detail.centerLocation;
            if (!latitude || !longitude) {
                return;
            }
            try {
                // 将 GCJ-02 坐标转换为百度坐标用于获取地址
                const baiduCoords = this.gcj02ToBaidu(latitude, longitude);
                // 获取地址信息
                const address = await this.getAddressFromLocation(
                    baiduCoords.lat,
                    baiduCoords.lng,
                );
                if (!address || !address.address) {
                    return;
                }
                // 更新当前位置信息
                this.currentLocation = {
                    latitude: baiduCoords.lat,
                    longitude: baiduCoords.lng,
                    gcjLatitude: latitude,
                    gcjLongitude: longitude,
                    address: address.address,
                    province: address.province,
                    city: address.city,
                    district: address.district,
                    street: address.street,
                    streetNumber: address.streetNumber,
                };
                // 添加标记点并显示地址信息
                this.addMarker(latitude, longitude, address.address);
                // 通知父组件位置已更新
                this.$emit('locationSelected', this.currentLocation);
            } catch (error) {
                console.error('处理地图区域改变事件失败:', error);
            }
        },
 
        // 添加标记点
        addMarker(latitude, longitude, title = '') {
            // 清除之前的标记点
            this.markers = [];
            // 添加新的标记点
            this.markers.push({
                id: this.selectedMarkerId++,
                latitude,
                longitude,
                title,
                width: 20,
                height: 20,
                callout: {
                    content: title || '未知位置',
                    color: '#000000',
                    fontSize: 14,
                    borderRadius: 4,
                    padding: 8,
                    display: 'ALWAYS', // 始终显示
                    bgColor: '#ffffff', // 背景色
                    borderWidth: 1, // 边框宽度
                    borderColor: '#cccccc', // 边框颜色
                    textAlign: 'center', // 文字居中
                    anchorY: -10, // 向上偏移,使文字显示在标记点上方
                },
            });
        },
 
        // 地图点击事件
        async handleMapTap(e) {
            if (!e || !e.detail) {
                return;
            }
            const { latitude, longitude } = e.detail;
            if (!latitude || !longitude) {
                return;
            }
            try {
                // 更新本地坐标
                this.localLatitude = latitude;
                this.localLongitude = longitude;
                // 将 GCJ-02 坐标转换为百度坐标用于获取地址
                const baiduCoords = this.gcj02ToBaidu(latitude, longitude);
                // 获取地址信息
                const address = await this.getAddressFromLocation(
                    baiduCoords.lat,
                    baiduCoords.lng,
                );
                if (!address || !address.address) {
                    Taro.showToast({
                        title: '获取地址失败',
                        icon: 'none',
                    });
                    return;
                }
                this.currentLocation = {
                    latitude: baiduCoords.lat,
                    longitude: baiduCoords.lng,
                    gcjLatitude: latitude,
                    gcjLongitude: longitude,
                    address: address.address,
                    province: address.province,
                    city: address.city,
                    district: address.district,
                    street: address.street,
                    streetNumber: address.streetNumber,
                };
                // 添加标记点
                this.addMarker(latitude, longitude, address.address);
                this.$emit('locationSelected', this.currentLocation);
            } catch (error) {
                console.error('处理地图点击事件失败:', error);
                Taro.showToast({
                    title: '获取地址失败',
                    icon: 'none',
                });
            }
        },
 
        // 标记点点击事件
        async handleMarkerTap(e) {
            const { markerId } = e.detail;
            const marker = this.markers.find(m => m.id === markerId);
            if (marker) {
                // 转换为百度坐标
                const baiduCoords = this.gcj02ToBaidu(marker.latitude, marker.longitude);
                // 获取地址信息
                const address = await this.getAddressFromLocation(
                    baiduCoords.lat,
                    baiduCoords.lng,
                );
                this.currentLocation = {
                    latitude: baiduCoords.lat,
                    longitude: baiduCoords.lng,
                    gcjLatitude: marker.latitude,
                    gcjLongitude: marker.longitude,
                    address: address.address,
                    province: address.province,
                    city: address.city,
                    district: address.district,
                    street: address.street,
                    streetNumber: address.streetNumber,
                };
                this.$emit('locationSelected', this.currentLocation);
            }
        },
 
        // 移动到指定位置
        moveToLocation(latitude, longitude) {
            // 更新地图位置数据
            this.mapLatitude = latitude;
            this.mapLongitude = longitude;
            this.mapScale = 16; // 设置合适的缩放级别
            // 使用地图上下文移动到指定位置
            if (this.mapCtx) {
                this.mapCtx.moveToLocation({
                    latitude: latitude,
                    longitude: longitude,
                    success: () => {
                        // 更新标记点位置
                        if (this.currentLocation) {
                            this.addMarker(
                                latitude,
                                longitude,
                                this.currentLocation.address,
                            );
                        }
                    },
                    fail: err => {
                        console.error('移动失败:', err);
                        // 失败时也要尝试更新标记点
                        if (this.currentLocation) {
                            this.addMarker(
                                latitude,
                                longitude,
                                this.currentLocation.address,
                            );
                        }
                    },
                });
            } else {
                // 地图上下文不可用时,直接更新标记点
                if (this.currentLocation) {
                    this.addMarker(latitude, longitude, this.currentLocation.address);
                }
            }
        },
 
        // 获取当前位置按钮点击事件
        async handleGetLocation(e) {
            try {
                // 显示加载中提示
                Taro.showLoading({
                    title: '获取位置中...',
                });
                const res = await Taro.getLocation({
                    type: 'gcj02',
                });
                // 更新本地坐标
                this.localLatitude = res.latitude;
                this.localLongitude = res.longitude;
                // 设置标志,防止handleRegionChange触发时覆盖地址
                this.isFromChooseLocation = true;
                // 将 GCJ-02 坐标转换为百度坐标用于获取地址
                const baiduCoords = this.gcj02ToBaidu(res.latitude, res.longitude);
                // 获取地址信息
                const address = await this.getAddressFromLocation(
                    baiduCoords.lat,
                    baiduCoords.lng,
                );
                this.currentLocation = {
                    latitude: baiduCoords.lat,
                    longitude: baiduCoords.lng,
                    gcjLatitude: res.latitude,
                    gcjLongitude: res.longitude,
                    address: address.address,
                    province: address.province,
                    city: address.city,
                    district: address.district,
                    street: address.street,
                    streetNumber: address.streetNumber,
                };
                // 直接更新地图位置
                this.mapLatitude = res.latitude;
                this.mapLongitude = res.longitude;
                this.mapScale = 16;
                // 添加标记点
                this.addMarker(res.latitude, res.longitude, address.address);
                // 通知父组件位置已更新
                this.$emit('locationSelected', this.currentLocation);
                // 完成后隐藏加载提示
                Taro.hideLoading();
                // 使用延时恢复标志
                setTimeout(() => {
                    this.isFromChooseLocation = false;
                }, 800);
            } catch (error) {
                console.error('获取位置失败:', error);
                Taro.hideLoading();
                this.isFromChooseLocation = false;
                Taro.showToast({
                    title: '获取位置失败',
                    icon: 'none',
                });
            }
        },
 
        // 选择位置按钮点击事件
        async handleChooseLocation(e) {
            try {
                const res = await Taro.chooseLocation();
                // 设置标志,防止handleRegionChange触发时覆盖地址
                this.isFromChooseLocation = true;
                // 更新本地坐标
                this.localLatitude = res.latitude;
                this.localLongitude = res.longitude;
                // 转换为百度坐标
                const baiduCoords = this.gcj02ToBaidu(res.latitude, res.longitude);
                this.currentLocation = {
                    latitude: baiduCoords.lat,
                    longitude: baiduCoords.lng,
                    gcjLatitude: res.latitude,
                    gcjLongitude: res.longitude,
                    address: res.address,
                    name: res.name || '',
                    province: '',
                    city: '',
                    district: '',
                    street: '',
                    streetNumber: '',
                };
                // 直接更新地图位置和添加标记点
                this.mapLatitude = res.latitude;
                this.mapLongitude = res.longitude;
                this.mapScale = 16;
                // 添加标记点
                this.addMarker(res.latitude, res.longitude, res.address);
                // 使用地图上下文移动到选择的位置
                if (this.mapCtx) {
                    this.mapCtx.moveToLocation({
                        latitude: res.latitude,
                        longitude: res.longitude,
                        success: () => {
                            // 再次确保标记点显示
                            setTimeout(() => {
                                // 重置标志
                                this.isFromChooseLocation = false;
                            }, 800);
                        },
                        fail: err => {
                            console.error('移动失败:', err);
                            // 重置标志
                            this.isFromChooseLocation = false;
                        },
                    });
                }
                this.$emit('locationSelected', this.currentLocation);
            } catch (error) {
                console.error('选择位置失败:', error);
                // 重置标志
                this.isFromChooseLocation = false;
                Taro.showToast({
                    title: '选择位置失败',
                    icon: 'none',
                });
            }
        },
 
        // 保存位置按钮点击事件
        handleSaveLocation(e) {
            if (!this.currentLocation) {
                Taro.showToast({
                    title: '请先选择位置',
                    icon: 'none',
                });
                return;
            }
            this.$emit('saveLocation', this.currentLocation);
        },
 
        // 获取地址信息
        async getAddressFromLocation(latitude, longitude) {
            try {
                const res = await Taro.request({
                    url: `${BAIDU_MAP.apiUrl}/reverse_geocoding/v3/`,
                    data: {
                        ak: BAIDU_MAP.ak,
                        output: 'json',
                        coordtype: BAIDU_MAP.coordType,
                        location: `${latitude},${longitude}`,
                    },
                    timeout: 10000,
                });
                if (!res.data) {
                    throw new Error('百度地图API返回数据为空');
                }
                if (res.data.status === 0) {
                    const result = res.data.result;
                    return {
                        address: result.formatted_address,
                        province: result.addressComponent.province,
                        city: result.addressComponent.city,
                        district: result.addressComponent.district,
                        street: result.addressComponent.street,
                        streetNumber: result.addressComponent.street_number,
                    };
                } else {
                    return {
                        address: '获取地址失败',
                        province: '',
                        city: '',
                        district: '',
                        street: '',
                        streetNumber: '',
                    };
                }
            } catch (error) {
                console.error('获取地址异常:', error);
                throw error;
            }
        },
 
        // GCJ-02坐标转百度坐标
        gcj02ToBaidu(lat, lng) {
            const PI = 3.14159265358979324;
            const x_pi = (PI * 3000.0) / 180.0;
            const z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * x_pi);
            const theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * x_pi);
            const bd_lng = z * Math.cos(theta) + 0.0065;
            const bd_lat = z * Math.sin(theta) + 0.006;
            return {
                lat: bd_lat,
                lng: bd_lng,
            };
        },
 
        // 百度坐标转腾讯坐标
        baiduToGcj02(lat, lng) {
            const PI = 3.14159265358979324;
            const x_pi = (PI * 3000.0) / 180.0;
            const x = lng - 0.0065;
            const y = lat - 0.006;
            const z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
            const theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
            const gg_lng = z * Math.cos(theta);
            const gg_lat = z * Math.sin(theta);
            return {
                lat: gg_lat,
                lng: gg_lng,
            };
        },
 
        // 初始化位置信息
        async initLocation() {
            try {
                // 设置标志,防止handleRegionChange触发时覆盖地址
                this.isFromChooseLocation = true;
                // 显示加载提示
                Taro.showLoading({
                    title: '加载位置信息...',
                });
                try {
                    // 使用本地坐标(初始默认值或props传入值)获取地址信息
                    const address = await this.getAddressFromLocation(
                        this.localLatitude,
                        this.localLongitude,
                    );
                    if (!address || !address.address) {
                        console.warn('获取地址信息失败');
                        Taro.hideLoading();
                        this.isFromChooseLocation = false;
                        return;
                    }
                    // 将百度坐标转换为腾讯坐标
                    const gcjCoords = this.baiduToGcj02(
                        this.localLatitude,
                        this.localLongitude,
                    );
                    // 更新当前位置信息
                    this.currentLocation = {
                        latitude: this.localLatitude,
                        longitude: this.localLongitude,
                        gcjLatitude: gcjCoords.lat,
                        gcjLongitude: gcjCoords.lng,
                        address: address.address,
                        province: address.province,
                        city: address.city,
                        district: address.district,
                        street: address.street,
                        streetNumber: address.streetNumber,
                    };
                    // 使用腾讯坐标更新地图位置
                    this.mapLatitude = gcjCoords.lat;
                    this.mapLongitude = gcjCoords.lng;
                    this.mapScale = 16;
                    // 添加标记点
                    this.markers = [
                        {
                            id: this.selectedMarkerId++,
                            latitude: gcjCoords.lat,
                            longitude: gcjCoords.lng,
                            title: address.address,
                            width: 30,
                            height: 30,
                            callout: {
                                content: address.address || '未知位置',
                                color: '#000000',
                                fontSize: 14,
                                borderRadius: 4,
                                padding: 8,
                                display: 'ALWAYS',
                                bgColor: '#ffffff',
                                borderWidth: 1,
                                borderColor: '#cccccc',
                                textAlign: 'center',
                                anchorY: -10,
                            },
                        },
                    ];
                    // 通知父组件位置已更新
                    this.$emit('locationSelected', this.currentLocation);
                    // 隐藏加载提示
                    Taro.hideLoading();
                    // 使用地图上下文移动到位置中心
                    if (this.mapCtx) {
                        this.mapCtx.moveToLocation({
                            latitude: gcjCoords.lat,
                            longitude: gcjCoords.lng,
                            success: () => {
                                // 延迟重置标志
                                setTimeout(() => {
                                    this.isFromChooseLocation = false;
                                }, 800);
                            },
                            fail: err => {
                                console.error('地图移动失败:', err);
                                this.isFromChooseLocation = false;
                            },
                        });
                    } else {
                        this.isFromChooseLocation = false;
                    }
                } catch (error) {
                    console.error('处理位置信息失败:', error);
                    Taro.hideLoading();
                    this.isFromChooseLocation = false;
                }
            } catch (error) {
                console.error('初始化位置信息失败:', error);
                Taro.hideLoading();
                this.isFromChooseLocation = false;
            }
        },
    },
};
</script>