场景: 进入小程序时, 需要获取用户的位置
getLocation(){
// 向用户发起授权请求
uni.authorize({
scope: "scope.userLocation", // 位置授权
success:(res) => {
// 发起授权成功----> 用户同意授权
// uni.getLocation ----> 获取当前的地理位置
uni.getLocation({
type: 'wgs84', // wgs84 返回 gps 坐标
success: (res)=>{ // 同意授权 -- > 并获取成功
// 得到 经纬度
longitude = res.longitude
latitude = res.latitude
// 根据经纬度获取具体位置: 例如百度定位
},
fail:(err) => { // 同意授权 -- > 但是授权失败(原因可能是因为用户手机未开启定位等)
// 调起客户端小程序设置界面
uni.getSetting({
success: (res) => {
if (!res.authSetting['scope.userLocation']) {
uni.showModal({
title: "打开定位授权",
success : (res) => {
if (res.confirm) {
uni.openSetting({
success: (open) => {
uni.getLocation({
type: 'wgs84',
success: (res)=>{
longitude = res.longitude
latitude = res.latitude
// 根据经纬度获取具体位置: 例如百度定位
}
});
}
})
} else if (res.cancel) {
}
}
})
} else {
// 当用户手机没有开通定位功能时
wx.showModal({
title: '您手机定位功能没有开启',
content: '请在系统设置中打开定位服务',
showCancel:false,
success : () => {
// 提示用户开启手机定位功能
// 进入首页
}
})
}
}
})
}
})
},
fail: (err)=>{
// 发起授权失败 ----> 用户拒绝授权
}
})
}
也可以直接用如下方法
getLocation(){
// 向用户发起授权请求
uni.authorize({
scope: "scope.userLocation", // 位置授权
success:(res) => {
// 发起授权成功----> 用户同意授权
// uni.getLocation ----> 获取当前的地理位置
uni.getLocation({
type: 'wgs84', // wgs84 返回 gps 坐标
success: (res)=>{ // 同意授权 -- > 并获取成功
// 得到 经纬度
longitude = res.longitude
latitude = res.latitude
// 根据经纬度获取具体位置: 例如百度定位
},
fail:(err) => { // 同意授权 -- > 但是授权失败(原因可能是因为用户手机未开启定位等)
// 当用户手机没有开通定位功能时
wx.showModal({
title: '您手机定位功能没有开启',
content: '请在系统设置中打开定位服务',
showCancel:false,
success : () => {
// 提示用户开启手机定位功能
// 进入首页
}
})
}
})
},
fail: (err)=>{
// 发起授权失败 ----> 用户拒绝授权
}
})
}
若在开始进入页面时,用户拒绝定位, 后面需要重新打开小程序定位, 可用如下方法:
uni.getSetting({
success: (result) => {
uni.showModal({
title: "打开定位授权",
success : (res) => {
if (res.confirm) {
uni.openSetting({
success: (open) => {
uni.getLocation({
type: 'wgs84',
success: (res)=>{
longitude = res.longitude
latitude = res.latitude
// 根据百度地图经纬度获取具体位置
}
});
}
})
} else if (res.cancel) {
}
}
})
}
})