index.vue
3.02 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
<template>
<div style="position: relative;width: 100%;">
<div id="mapContainer" class="map"></div>
<!-- <div id="addressInfo" class="address-info">
<p v-if="address">地址: {{ address }}</p>
<p v-if="center">地址: {{ lat }}</p>
<p v-if="center">地址: {{ lng }}</p>
<p v-else>加载中...</p>
</div> -->
</div>
</template>
<script>
export default {
name: 'TencentMap',
props: {
lat: {
type: Number,
default: 30.67
},
lng: {
type: Number,
default: 104.06
},
},
data() {
return {
map: null,
marker: null,
address: ''
};
},
mounted() {
// 初始化地图
this.initMap();
},
methods: {
initMap() {
// 将经纬度转换为腾讯地图的LatLng对象
const centerLatLng = new qq.maps.LatLng(this.lat, this.lng);
// 创建地图实例
this.map = new qq.maps.Map(document.getElementById('mapContainer'), {
center: centerLatLng,
zoom: 13
});
// 创建标记
this.marker = new qq.maps.Marker({
position: centerLatLng,
map: this.map
});
// 添加点击事件监听器
// qq.maps.event.addListener(this.marker, 'click', this.onMarkerClick);
// 添加地图点击事件监听器
qq.maps.event.addListener(this.map, 'click', this.onMapClick);
// // 获取地址信息
// this.getAreaCode(this.lat, this.lng);
},
onMarkerClick() {
alert('您点击了标记点');
},
onMapClick(event) {
// 获取点击位置的经纬度
const newLatLng = event.latLng;
// 更新标记位置
this.marker.setPosition(newLatLng);
this.getAreaCode(newLatLng.getLat(), newLatLng.getLng());
// 更新父组件中的经纬度
// 获取新的地址信息
},
getAreaCode(lat, lng) {
let that = this;
//这里可以直接this.$jsonp地址传入你的经纬度;
that.$jsonp("https://apis.map.qq.com/ws/geocoder/v1/?", {
location: `${lat},${lng}`, // 经纬度
key: 'PGRBZ-Z3FRJ-DTYFB-XNX4X-DC6HZ-MCFYU', //这里就是要开启那个service不然会报错让你开启
output: "jsonp", // output必须jsonp 不然会超时
}).then((res) => {
if (res.message == 'Success') {
console.log(res);
that.address = res.result.address
that.$emit('updatecenter', {
lat: lat,
lng: lng,
address: that.address
});
} else {
this.$message.error(res.message)
}
}).catch(err => {
this.$message.error("获取城市编码失败")
console.error(err)
})
}
}
}
</script>
<style scoped>
.map {
width: 100%;
height: 300px;
}
.address-info {
position: absolute;
bottom: 0;
left: 0;
z-index: 999999;
background: #fff;
}
</style>