uniapp在所有平台获取定位权限大全

创作灵感:公司要我用uniapp开发了一套代码,分别在app、h5、微信公众号h5、小程序都使用,所以要根据不同平台做定位权限的获取,以下是每个平台获取权限的前提条件,代码会放在最后。

1,app

准备工作:在获取权限的时候你要准备一个弹窗告诉用户是否允许获取权限,用户点击允许才能获取,拒绝你要弹窗提醒用户关闭了定位权限,要他去系统打开,点击去设置重新打开,不然就会被疯狂打回(tmd,我就是这样,类似这样子,还要写清楚获取权限的目的:

2,h5和微信公众号h5差不多

获取权限很直接,允许就获取了,但是拒绝后还是要提醒用户打开电脑或者手机浏览器的定位

3,小程序

我这里是和app一样的处理,但是拒绝定位后,小程序的设置和app不同

好了,大概情况介绍完了,以上所有平台的位置权限我封装了一个函数,直接使用这个函数就可以了,以下是代码:

import store from "../store";
// #ifdef H5
//注意这个是微信公众号定位用的,要npm才能用
//npm install jweixin-module --save
const jWeixin = require('jweixin-module')
// #endif
import {
		isWXH5
	} from "./util"
这个方法我写在别的地方,你们可以直接写在这里
// function isWXH5() {
// 	var ua = navigator.userAgent.toLowerCase();
// 	if (ua.match(/MicroMessenger/i) == 'micromessenger') {
// 		return true;
// 	} else {
// 		return false;
// 	}

// }
const mygetLocation=(successCallback, errorCallback)=> {
	let that = this;

	uni.getLocation({
		type: 'gcj02',
		geocode: true,
		success: (res) => {
			// that.showCard = false;

			// 调用传入的成功回调
			if (typeof successCallback === 'function') {
				successCallback(res);
			}
			

		},
		fail: async (err) => {
			// 调用传入的错误回调
			if (typeof errorCallback === 'function') {
				errorCallback(err);
			}

			// 处理不同平台的定位逻辑
			// #ifndef MP-WEIXIN
			
			if (!isWXH5()) {
				checkOpenGPSService();
			} else {
				jWeixin.getLocation({
					type: 'gcj02',
					success(res) {
				

						// 调用传入的成功回调
						if (typeof successCallback === 'function') {
							successCallback(res);
						}

					}
				});
			}
			// #endif

			// #ifdef MP-WEIXIN
			uni.showModal({
				title: '提示',
				content: '请打开定位权限',
				showCancel: true,
				cancelText: '取消',
				cancelColor: '#000000',
				confirmText: '确定',
				confirmColor: '#AB80FF',
				success: res => {
					if (res.confirm) {
						uni.openSetting({
							success(res) {
								if (res.authSetting["scope.userLocation"]) {
									uni.getLocation({
										type: 'wgs84',
										success(res) {
										

											// 调用传入的成功回调
											if (typeof successCallback ===
												'function') {
												successCallback(res);
											}

										}
									});
								}
							},
							fail(err) {
								console.log(err);
							}
						});
					} else if (res.cancel) {
						console.log('用户点击取消');
						wx.showToast({
							title: '需要定位权限',
							icon: 'none',
							duration: 2000,
						});
					}
				}
			});
			// #endif
		}
	});
}

const checkOpenGPSService=()=> {
	const that = this
	let systemType = uni.getSystemInfoSync().platform;
	// #ifdef APP
	// 安卓
	const systemSetting = uni.getSystemSetting()
	console.log(systemSetting)
	if (!systemSetting.locationEnabled) {
		// if (self.$refs.confirmPopup) {
		store.commit('userInfo/setISlocal', false);

		uni.showModal({
			title: 'APP系统定位功能未开启',
			content: '请在手机系统“设置”权限管理中开启“位置信息”权限该功能用于提供基于地理位置的功能或服务。',
			confirmText: '前往设置',
			showCancel: false,
			success: (res) => {
				if (res.confirm) {
					openGPSServiceByAndroidIOS()
				}
			}
		})



		return false
	}

	const appAuthorizeSetting = uni.getAppAuthorizeSetting()

	if (appAuthorizeSetting.locationAuthorized == 'denied') {
		
		uni.showModal({
			title: 'APP位置权限未开启',
			content: '您已拒绝获取定位权限,是否去设置中打开?',
			confirmText: '前往设置',
			showCancel: false,
			success: (res) => {
				if (res.confirm) {
					uni.openAppAuthorizeSetting()
				}
			}
		})
		

		return false
	}

	// #ifdef H5
	getMyPosition();
	// #endif


}

function getMyPosition() {
	const res = uni.getAppAuthorizeSetting();

	if (window.navigator.geolocation) {
	
		//获取当前位置..
		//如果获取位置成功,会调用名字为successPosition 的方法.
		navigator.geolocation.getCurrentPosition(successPosition, errorPosition);
	} else {
		store.commit('userInfo/setISlocal', false);
		alert("您当前的浏览器不支持..");
	}
}

function successPosition(position) {
	let jd = position.coords.longitude; //经度
	let wd = position.coords.latitude; //纬度
	// alert(jd + "," + wd);
}
//如果没有获取到位置,就会调用这个方法
function errorPosition() {
	uni.getLocation({
		type: 'gcj02',
		geocode: true,
		success: (res) => {


		},

	})
	uni.showToast({
		title: "请打开手机浏览器的定位服务~",
		icon: "none"
	})
}
// 请求定位权限
function requestLocationPermission() {
	if (store.state.userInfo.showSetting) {
		plus.android.requestPermissions(['android.permission.ACCESS_FINE_LOCATION'], (e) => {
			if (e.granted.length > 0) {
				// 权限已获得,可以进行定位操作
				console.log("定位权限已获得");
				store.commit('userInfo/setISlocal', true);
				getLocation();
			} else if (e.deniedAlways.length > 0 || e.deniedPresent.length > 0) {
				// 权限被拒绝,弹出提示框引导用户去设置
				showPermissionDialog();
				store.commit('userInfo/setISlocal', false);
			}
		});
	}
}

// 获取定位信息的示例函数
function getLocation() {
	plus.geolocation.getCurrentPosition((position) => {
		console.log('定位成功:', position);
		store.commit('userInfo/setISlocal', true);
		// 处理定位信息,例如:
		// store.commit('userInfo/setLocation', position);
	}, (error) => {
		console.error('定位失败:', error);
	});
}

// 显示权限设置的对话框
function showPermissionDialog() {
	console.log(store.state.userInfo.showSetting);
	if (store.state.userInfo.showSetting) {
		uni.showModal({
			title: '权限提示',
			content: '请前往设置中开启定位权限',
			showCancel: true,
			confirmText: '去设置',
			cancelText: '取消',
			success(res) {
				if (res.confirm) {
					let Intent = plus.android.importClass('android.content.Intent');
					let Settings = plus.android.importClass('android.provider.Settings');
					let mainActivity = plus.android.runtimeMainActivity();
					let intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
					let uri = plus.android.importClass('android.net.Uri').fromParts("package", mainActivity
						.getPackageName(), null);
					intent.setData(uri);
					try {
						mainActivity.startActivity(intent);
					} catch (error) {
						console.error("打开设置页面失败:", error);
					}
				}
			}
		});
	}
}

// 检查定位服务是否启用
function checkLocationService() {
	let context = plus.android.importClass('android.content.Context');
	let locationManager = plus.android.importClass('android.location.LocationManager');
	let main = plus.android.runtimeMainActivity();
	let mainSvr = main.getSystemService(context.LOCATION_SERVICE);

	if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
		if (store.state.userInfo.showSetting) {

			console.log('定位服务未启用');
			// 可以在这里提示用户启用定位服务
			uni.showModal({
				title: '提示',
				content: '请打开定位服务功能',
				showCancel: true,
				cancelText: "取消",
				confirmText: "去设置",
				success(res) {
					if (res.confirm) {
						let intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
						main.startActivity(intent); // 打开系统设置定位服务功能页面
					}
				}
			});
		}
	} else {
		// 定位服务已启用,继续请求权限
		requestLocationPermission();
	}
}
module.exports = {
	checkOpenGPSService,
	mygetLocation
}

以上代码可以直接使用,获取到定位你可以自行处理定位数据,定位失败不用处理,会自己提醒,使用方法:


//引入函数
import {
		mygetLocation
	} from "@/utils/location.js"
在methods里当用户点击定位/确定定位按钮时使用
mygetLocation(
					(res) => {
						console.log('定位成功:', res);
						

						// 在这里处理成功后的逻辑
					},
					(err) => {
						console.error('定位失败:', err);
						// 在这里处理失败后的逻辑
					}
				);

耶耶耶耶耶耶耶耶!大功告成!! 俺集所有大神代码自己封装的特别全面的函数,俺真牛!!!(其实这几天才封装,私密马赛!!!

如果能帮到大家,请多多给我点赞谢谢!!!!

大家如果有其他问题欢迎一起讨论!还有什么要问的也可以问哦,好久没更文章了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值