首先先配置小程序位置
在manifest.json文件中,打开源码视图

在源码视图中,找到小程序相关添加上图中蓝色圈起的部分

最后直接上代码
// 获取当前用户的位置
getUserLocation(){
let that = this
uni.getSetting({
success: (res) => {
let authStatus = res.authSetting['scope.userLocation'];
// 如果没有授权位置
if(!authStatus){
//向用户发起授权请求
console.log('授权')
uni.authorize({
scope: "scope.userLocation",
success: (res) => {
// console.log(res)
uni.getLocation({
type: 'wgs84',
geocode:true,//设置该参数为true可直接获取经纬度及城市信息
success: function (res) {
console.log(res)
that.reportContent.lat = res.latitude
that.reportContent.lon = res.longitude
that.reportContent.lonlat = '[' + res.longitude + ',' + res.latitude + ']'
},
fail: function () {
uni.showToast({
title: '获取地址失败,请打开手机的定位服务',
icon:'none',
duration: 1500
});
}
});
},
fail: (err) => {
console.log(err)
uni.showModal({
title: '授权失败',
content: '需要获取您当前位置,请在设置界面打开相关权限',
success: (res) => {
if (res.confirm) {
uni.openSetting()
}
}
})
}
})
}else{
console.log('已授权')
uni.getLocation({
type: 'wgs84',
geocode:true,//设置该参数为true可直接获取经纬度及城市信息
success: function (res) {
console.log(res)
that.reportContent.lat = res.latitude
that.reportContent.lon = res.longitude
that.reportContent.lonlat = '[' + res.longitude + ',' + res.latitude + ']'
},
fail: function () {
uni.showToast({
title: '获取地址失败,请打开手机的定位服务',
icon:'none'
});
}
});
}
}
})
},
原创文章,作者:3628473679,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/278526.html