需求描述:当用户进入H5页面时,自动获取用户的经纬度,通过经纬度获取当前城区的adCode
那么为什么不用高德地图而用腾讯地图呢?因为在使用高德地图时,获取精确定位的api不稳定,而另一个api又无法获取具体城区的adCode,只能获取当前城市的adCode,所以就采用了腾讯地图
使用流程:
第一步在index.html中引入:
<script src="https://map.qq.com/api/gljs?v=1.exp&key=腾讯地图key"></script>
第二步在要使用的页面中:
export default {
data() {
return {
mapKey: '腾讯地图的key', // 腾讯地图的key
lat: '',
lng: '',
}
},
mounted() {
// 1初始化腾讯地图
this.geolocation = new qq.maps.Geolocation(this.mapKey, 'myapp')
// 2开始定位
this.getMyLocation()
},
methods:{
// 获取当前位置
getMyLocation() {
this.geolocation.getLocation(this.showPosition, this.errorPosition) //开启定位
},
// 定位成功时的函数
showPosition(position) {
this.lat = position.lat
this.lng = position.lng
this.getAreaCode()
},
//定时失败时的函数
errorPosition() {
this.$toast('请检查是否开启了定位')
},
getAreaCode() {
const _this = this
//这里可以直接this.$jsonp地址传入你的经纬度;
this.$jsonp('https://apis.map.qq.com/ws/geocoder/v1/?', {
location: `${this.lat},${this.lng}`, // 经纬度
key: this.mapKey,
output: 'jsonp' // output必须jsonp 不然会超时
}).then(res => {
//获取到的res 就是地址的所有信息,包括adCode
})
}
}