微信小程序提供的接口只能获得用户的经纬度
wx.getLocation(Object)
可以通过腾讯提供的位置位置服务接口解析经纬度来获取地址信息
首先进入腾讯位置服务官网http://lbs.qq.com/index.html
在右上角选择"接入指引"
~ 完成图中前三个步骤就Ok了,主要是获得开发密钥(Key)
~ 接下来在首页,选择"开发"下的"WebService API",进入里面有接口相关的使用信息
~ 下面是代码展示
wx.getLocation({ //没有特别说明的都是固定写法
type: 'wgs84',
success: function (res) {
console.log('location', res);
var locationString = res.latitude + "," + res.longitude;
wx.request({
url: 'http://apis.map.qq.com/ws/geocoder/v1/',
data: {
"key": "xxxx-xxxx-xxxx-xxxx-xxxx-xxxx",
"location": locationString
},
method: 'GET',
success: function (r) {
//输出一下位置信息
console.log('用户位置信息',r.data.result.address);
//r.data.result.address获得的就是用户的位置信息,将它保存到一个全局变量上
getApp().globalData.locationInfo = r.data.result.address;
//这步是将位置信息保存到本地缓存中,key = value的形式
try {
wx.setStorageSync('locationInfo', r.data.result.address)
} catch (e) {
console.log(e)
}
}
});
}
});