1.在app.json/uniapp.json中声明permission
{
"pages": [
"pages/home/index",
"pages/promote/index",
"pages/partner/index/index",
"pages/my/index",
"pages/login/wxmp"
],
"permission":{
"scope.userLocation":{
"desc":"获取当前位置"
}
},
}
2. 首先调用wx.getLocation获得当前位置经纬度
2.1腾讯官网:https://lbs.qq.com/
2.1.2如何申请key:https://baijiahao.baidu.com/s?id=1622891654704256153&wfr=spider&for=pc
2.1.3一定要在小程序后台把域名加到服务器域名中否则真机调试获取不到详细地址:
|
ps:之所以前缀是uni开头是因为我用uniapp开发的,原生开发的直接把uni改成wx
//第一步
getLocationt: function() {
const that = this;
// 首先调用wx.getLocation获得当前位置经纬度
uni.getLocation({
type: 'gcj02',
success: function(res) {
// 腾讯api:https://apis.map.qq.com/ws/geocoder/v1/。key要自己去申请
var url = 'https://apis.map.qq.com/ws/geocoder/v1/?location=' + res.latitude + ',' + res.longitude + '&key=dlskdlsf ';
uni.request({
url: url,
success: (result) => {
that.applyaddress = result.data.result.address;
console.log('address', that.applyaddress);
}, fail(res) {
console.log('失败了', res, url);
},
});
},
});
},
//第二步
// 授权失败重新调用
openlocation() {
var that = this;
uni.getSetting({
success: (res) => {
if (res.authSetting['scope.userLocation'] !== undefined && res.authSetting['scope.userLocation'] !== true) { // 非初始化进入该页面,且未授权
uni.showModal({
title: '授权当前位置',
content: '需要获取您的当前位置,
success: function(res) {
if (res.cancel) {
uni.showToast({
title: '授权当前位置失败,请重新授权',
icon: 'none',
});
} else if (res.confirm) {
uni.openSetting({
success: function(dataAu) {
if (dataAu.authSetting['scope.userLocation'] === true) {
// 再次授权,调用getLocationt的API
that.getLocationt();
}
},
});
}
},
});
} else if (res.authSetting['scope.userLocation'] === undefined) { // 初始化进入
that.getLocationt();
} else { // 授权后默认加载
that.getLocationt();
}
},
});
},