肯定很多新入手小程序的小伙伴对于小程序定位获取不了城市信息的事情烦恼吧,今天在这里由我来给小伙伴们讲解一下如何编写代码以及配置小程序获取城市信息吧
首先我们需要获取当前位置的经纬度,通过经纬度来转化成当前城市的信息我这里用到了uni的api“uni.getLoaction”我们在使用“uni.getLoaction”的时候需要先在小程序里进行配置
我们在微信公共平台申请好微信小程序后,信息完善之后,目录里找到【开发】=>【开发管理】=>【接口设置】找到地理位置并申请开通【wx.getLocation】
![](https://img-blog.csdnimg.cn/img_convert/f267ce36a9ec82628ec8a365d8d86518.png)
开通好之后我们就能通过uni.getLocation获取经纬度了
uni.getLocation({
type: 'gcj02',
success: (res) => {
this.lat = res.latitude;
this.lng = res.longitude;
}
});
逆地理解析需要借助三方的sdk,所以我们需要在代码里引入高德的sdk,前往高德开放平台下载sdk
并在申请高德key不会请参考高德key申请指引申请完成之后我们来看代码
//引入三方的sdk
import amap from '@/libs/amap-wx.js'
//声明变量key
export default {
data() {
return {
amapPlugin: null, //new地图
positions: {
text: '',
lng: '',
lat: ''
},
key: '948a6ee9f2f971b1e4893eb09f7244ab',
}
},
//在onLoad里请求高德的接口
onLoad(options) {
this.amapPlugin = new amap.AMapWX({
key: this.key
});
},
//再写一个方法来获取经纬度并转化城市信息
relocate() {
let that = this
uni.getLocation({
type: 'gcj02',
success: (res) => {
that.amapPlugin.getRegeo({
location: `${res.longitude},${res.latitude} `,
success: (addr) => {
console.log('addr',addr)
console.log(addr[0])
let datas = addr[0].regeocodeData.addressComponent
that.positions.text = datas.city;
console.log('addr[0].regeocode',addr[0].regeocodeData);
that.positions.lat = res.latitude;
that.positions.lng = res.longitude;
},
fail: (err) => {
}
});
}
});
},
这样就能请求成功了