当前位置:   article > 正文

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

uniapp获取定位授权

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



效果图

Android设备

在这里插入图片描述

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

在这里插入图片描述


创建js文件

permission.js
  • 新建 .js 文件,例: permission.js
  • 管理相关权限,例相册、相机等,可以写在此文件中
  • 根据不同平台,处理向系统请求权限
/// 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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101

location.js
  • 检测当前权限
  • 获取当前位置
  • 拒绝授权,弹窗提示
  • 跳转App应用设置,打开位置权限
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;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83

使用

<button type="primary" @click="getLocation">获取位置</button>
  • 1

import location from '@/common/js/location.js'

/**
 * 获取位置
 */
getLocation() {
    location.getLocation();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

  • 回调
location.getLocation((res) => {
    if (res != 1) return;

    // xxx
});
  • 1
  • 2
  • 3
  • 4
  • 5

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/544344
推荐阅读