需求:在小程序首页需要显示用户所在城市
。
解决方案:使用wx.getLocation
获取经纬度坐标,再使用微信小程序JavaScript SDK
的地址逆解析方法reverseGeocoder
,就可以完美搞定。
微信小程序JavaScript SDK官方地址 https://lbs.qq.com/qqmap_wx_jssdk/index.html
我的实现:
1、首先申请腾讯地图密钥key,特别要注意域名白名单
的填写。
2、安装qqmap-wx-jssdk
大家可以从官网直接下载使用,我是使用npm
包的方式安装
yarn add qqmap-wx-jssdk
3、核心代码
const QQMapWX = require('qqmap-wx-jssdk');
export default {
data() {
return {
qqmapsdk: null,
}
},
methods:{
// 获取当前位置经纬度
async getCurrentPosition() {
const self = this
// 获取经纬度
const { latitude, longitude } = await new Promise((resolve, reject) => {
wx.getLocation({
type: 'gcj02',
success(res) {
resolve(res)
}
})
})
// 获取地址信息
this.qqmapsdk.reverseGeocoder({
location: {
latitude: latitude,
longitude: longitude
},
success: function (res) {
const { result } = res
const { address } = result
// 打印看看吧
console.log(result);
},
fail: function (res) {
console.log(res)
}
})
}
},
onLoad() {
this.qqmapsdk = new QQMapWX({ key: 'PW2BZ-3WDWD-4X44T-PDRF2-D6Z3Q-I4FA5' })
this.getCurrentPosition()
}
}
4、最后记得,要配置一下合法域名
。