uniapp获取当前位置及检测授权状态

uniapp获取当前位置及检测授权定位权限

文章目录

效果图

Android设备

  • 点击 "设置",跳转应用信息,打开"权限即可";

创建js文件

permission.js
  • 新建 .js 文件,例: permission.js
  • 管理相关权限,例相册、相机等,可以写在此文件中
  • 根据不同平台,处理向系统请求权限
javascript 复制代码
/// null = 未请求,1 = 已允许,0 = 拒绝|受限, 2 = 系统未开启

var isIOS

function location() {
    var result = 0;
    var cllocationManger = plus.ios.import("CLLocationManager");
    var enable = cllocationManger.locationServicesEnabled();
    var status = cllocationManger.authorizationStatus();
    if (!enable) {
        result = 2;
    } else if (status === 0) {
        result = null;
    } else if (status === 3 || status === 4) {
        result = 1;
    } else {
        result = 0;
    }
    plus.ios.deleteObject(cllocationManger);
    return result;
}

function requestIOS(permissionID) {
    return new Promise((resolve, reject) => {
        switch (permissionID) {
            case "location":
                resolve(location());
                break;
            default:
                resolve(0);
                break;
        }
    });
}

function requestAndroid(permissionID) {
    return new Promise((resolve, reject) => {
        plus.android.requestPermissions(
            [permissionID],
            function(resultObj) {
                var result = 0;
                for (var i = 0; i < resultObj.granted.length; i++) {
                    var grantedPermission = resultObj.granted[i];
                    console.log('已获取的权限:');
                    result = 1
                }
                for (var i = 0; i < resultObj.deniedPresent.length; i++) {
                    var deniedPresentPermission = resultObj.deniedPresent[i];
                    console.log('拒绝本次申请的权限:');
                    result = 0
                }
                for (var i = 0; i < resultObj.deniedAlways.length; i++) {
                    var deniedAlwaysPermission = resultObj.deniedAlways[i];
                    console.log('永久拒绝申请的权限:');
                    result = -1
                }
                resolve(result);
            },
            function(error) {
                resolve({
                    code: error.code,
                    message: error.message
                });
            }
        );
    });
}

function gotoAppPermissionSetting() {
    if (permission.isIOS) {
        var UIApplication = plus.ios.import("UIApplication");
        var application2 = UIApplication.sharedApplication();
        var NSURL2 = plus.ios.import("NSURL");
        var setting2 = NSURL2.URLWithString("app-settings:");
        application2.openURL(setting2);
        plus.ios.deleteObject(setting2);
        plus.ios.deleteObject(NSURL2);
        plus.ios.deleteObject(application2);
    } else {
        var Intent = plus.android.importClass("android.content.Intent");
        var Settings = plus.android.importClass("android.provider.Settings");
        var Uri = plus.android.importClass("android.net.Uri");
        var mainActivity = plus.android.runtimeMainActivity();
        var intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
        intent.setData(uri);
        mainActivity.startActivity(intent);
    }
}

const permission = {
    get isIOS(){
        return typeof isIOS === 'boolean' ? isIOS : (isIOS = uni.getSystemInfoSync().platform === 'ios')
    },
    requestIOS: requestIOS,
    requestAndroid: requestAndroid,
    gotoAppSetting: gotoAppPermissionSetting
}

export default permission
location.js
  • 检测当前权限
  • 获取当前位置
  • 拒绝授权,弹窗提示
  • 跳转App应用设置,打开位置权限
javascript 复制代码
import permision from '@/common/js/permission.js'
import store from '@/store/index.js'

export async function getLocation(cb) {
	// #ifdef APP-PLUS
	let status = await checkPermission();
	if (status !== 1) {
		return status;
	}
	// #endif
	
	if (typeof cb == 'function') cb && typeof cb == 'function' && cb(status)
	doGetLocation();
}

/**
 * 获取当前位置信息
 */
export const doGetLocation = () => {
	uni.getLocation({
		success: (res) => {
            // 根据个人所需处理
			store.commit('SET_LOCATION', {
				lng: res.longitude,
				lat: res.latitude
			});
			console.log('当前位置:', res.longitude, res.latitude);
		},
		fail: (err) => {
			if (err.errMsg.indexOf("auth deny") >= 0) {
				uni.showToast({
					title: "访问位置被拒绝",
					icon: 'none'
				})
			} else {
				uni.showToast({
					title: err.errMsg,
					icon: 'none'
				})
			}
		}
	})
}

/**
 * 检测定位权限
 */
async function checkPermission() {
	let status = permision.isIOS ? await permision.requestIOS('location') :
		await permision.requestAndroid('android.permission.ACCESS_FINE_LOCATION');

	if (status === null || status === 1) {
		status = 1;
	} else if (status === 2) {
		uni.showModal({
			content: "系统定位已关闭",
			showCancel: false,
			success: function(res) {}
		})
	} else if (status.code) {
		uni.showModal({
			content: status.message
		})
	} else {
		uni.showModal({
			content: "为了您更好的体验App蓝牙功能,需要获取位置信息,请点击设置开启定位权限",
			confirmText: "设置",
			success: function(res) {
				if (res.confirm) {
					permision.gotoAppSetting();
				}
			}
		})
	}

	return status;
}


const location = {
	getLocation
}
export default location;

使用

html 复制代码
<button type="primary" @click="getLocation">获取位置</button>
javascript 复制代码
import location from '@/common/js/location.js'

/**
 * 获取位置
 */
getLocation() {
    location.getLocation();
}
  • 回调
javascript 复制代码
location.getLocation((res) => {
    if (res != 1) return;

    // xxx
});
相关推荐
Smile_ping7 个月前
uniapp获取当前位置及检测授权状态——支持App、微信小程序
uniapp获取当前位置·getlocation·微信小程序获取当前位置·uniapp检测定位权限