uniapp得到用户当前定位以及用户选择位置

news/2024/11/26 0:39:37/

前言:

         使用uniapp的getLocation、chooseLocation封装获取位置信息,因多个页面都需要用到,所以定义在了app.vue中,避免重复编写代码

APP.vue: 

import utils from "@/utils/utils.js";
data() {return {isIos:false,hasLocation: false,location:{}};},
// <-----------位置相关开始---------->async getLocation(type) {// #ifdef APP-PLUS	let status = await this.checkPermission();if (status !== 1) {return;}// #endif// #ifdef MP-WEIXIN || MP-TOUTIAO || MP-QQlet status = await this.getSetting();if (status === 2) {this.showConfirm();return;}// #endifif(type=='getlocation'){this.doGetLocation();//得到用户当前经纬度}else if(type=='chouselocation'){let res = await this.doChouselocation()console.log(res);return  res;//用户选择位置}},doGetLocation() {uni.getLocation({success: res => {console.log(res);this.hasLocation = true;this.location = utils.formatLocation(res.longitude, res.latitude);this.$unistore.setUserLng(res.longitude)this.$unistore.setUserLat(res.latitude)},fail: err => {if (err.errMsg.indexOf('auth deny') >= 0) {uni.showToast({title: '访问位置被拒绝'});} else {uni.showToast({title: err.errMsg});}}});},doChouselocation(){return new Promise((reslove,reject)=>{uni.chooseLocation({success: (res)=> {// console.log(res);// console.log('位置名称:' + res.name);// console.log('详细地址:' + res.address);// console.log('纬度:' + res.latitude);// console.log('经度:' + res.longitude);reslove(res)},complete(){console.log("mapending");},fail(err){console.log(err);reject(err)}});})},// 获取用户当前格式--->主要针对微信小程序getSetting: function() {return new Promise((resolve, reject) => {uni.getSetting({success: res => {if (res.authSetting['scope.userLocation'] === undefined) {resolve(0);return;}if (res.authSetting['scope.userLocation']) {resolve(1);} else {resolve(2);}}});});},// 打开设置-->针对微信小程序openSetting: function() {this.hideConfirm();uni.openSetting({success: res => {if (res.authSetting && res.authSetting['scope.userLocation']) {this.doGetLocation();}},fail: err => {}});},async checkPermission(){let typeconst status = this.isIos ? await this.$myapppermision.judgeIosPermission('location') :await this.$myapppermision.requestAndroidPermission('android.permission.ACCESS_FINE_LOCATION');if (status === null || status === 1) {type = 1} else if (status === 2) {uni.showModal({content: '系统定位已关闭',confirmText: '确定',showCancel: false,success: function(res) {}});type = 2} else if(status==0){uni.showModal({title:"权限不够哦!",content:"为保证得到更好的服务,请重新设置定位权限",cancelText:"前去设置",cancelColor:"#888",confirmText:"我知道了",confirmColor:"#1A2486",success: (res)=>{if (res.confirm) {console.log('用户点击确定');} else if (res.cancel) {console.log('用户点击取消');this.$myapppermision.gotoAppPermissionSetting()}}})type = 0}return type;}
onload() {this.isIos = plus.os.name == 'iOS';},
onShow: function() {//因为用户当前位置全局都需要,所以我在页面显示时就执行定位,把用户的经纬度保存在store中this.getLocation('getlocation')},

Index.vue

在index.vue页面中使用app里的用户选取位置的方法

// 获取位置chouselocation(){let app = getApp()let res = app.getLocation('chouselocation')res.then((res)=>{//保存纬度至当前页面this.listQuery.formLat = res.latitude//保存经度至当前页面this.listQuery.formLng = res.longitude})},

需要用到的外部文件

utils.js

function formatLocation(longitude, latitude) {if (typeof longitude === 'string' && typeof latitude === 'string') {longitude = parseFloat(longitude)latitude = parseFloat(latitude)}longitude = longitude.toFixed(2)latitude = latitude.toFixed(2)return {longitude: longitude.toString().split('.'),latitude: latitude.toString().split('.')}
}
module.exports = {formatLocation: formatLocation,
}

判断各种权限的文件

在app.vue中会用到

permission.js

/*** 本模块封装了Android、iOS的应用权限判断、打开应用权限设置界面、以及位置系统服务是否开启*/
// null = 未请求,1 = 已允许,0 = 拒绝|受限, 2 = 系统未开启
var isIos
// #ifdef APP-PLUS
isIos = (plus.os.name == "iOS")
// #endif// 判断推送权限是否开启
function judgeIosPermissionPush() {var result = false;var UIApplication = plus.ios.import("UIApplication");var app = UIApplication.sharedApplication();var enabledTypes = 0;if (app.currentUserNotificationSettings) {var settings = app.currentUserNotificationSettings();enabledTypes = settings.plusGetAttribute("types");console.log("enabledTypes1:" + enabledTypes);if (enabledTypes == 0) {console.log("推送权限没有开启");} else {result = true;console.log("已经开启推送功能!")}plus.ios.deleteObject(settings);} else {enabledTypes = app.enabledRemoteNotificationTypes();if (enabledTypes == 0) {console.log("推送权限没有开启!");} else {result = true;console.log("已经开启推送功能!")}console.log("enabledTypes2:" + enabledTypes);}plus.ios.deleteObject(app);plus.ios.deleteObject(UIApplication);return result;
}// 判断定位权限是否开启
function judgeIosPermissionLocation() {var result = 0;var cllocationManger = plus.ios.import("CLLocationManager");// var status = cllocationManger.authorizationStatus();result = (status != 2)// console.log("定位权限开启:" + result);// 以下代码判断了手机设备的定位是否关闭,推荐另行使用方法 checkSystemEnableLocationvar enable = cllocationManger.locationServicesEnabled();var status = cllocationManger.authorizationStatus();// console.log("enable:" + enable);// console.log("status:" + status);if (!enable) {result = 2;//系统未开启console.log("手机定位服务已开启且已授予定位权限");} else if(status==0) {result = null //未请求console.log("手机系统的定位没有打开或未给予定位权限");} else if(status==3 || status ==4){result = 1 //已允许}else{result = 0 //拒绝|受限}plus.ios.deleteObject(cllocationManger);return result;
}// 判断麦克风权限是否开启
function judgeIosPermissionRecord() {var result = false;var avaudiosession = plus.ios.import("AVAudioSession");var avaudio = avaudiosession.sharedInstance();var permissionStatus = avaudio.recordPermission();console.log("permissionStatus:" + permissionStatus);if (permissionStatus == 1684369017 || permissionStatus == 1970168948) {console.log("麦克风权限没有开启");} else {result = true;console.log("麦克风权限已经开启");}plus.ios.deleteObject(avaudiosession);return result;
}// 判断相机权限是否开启
function judgeIosPermissionCamera() {var result = false;var AVCaptureDevice = plus.ios.import("AVCaptureDevice");var authStatus = AVCaptureDevice.authorizationStatusForMediaType('vide');console.log("authStatus:" + authStatus);if (authStatus == 3) {result = true;console.log("相机权限已经开启");} else {console.log("相机权限没有开启");}plus.ios.deleteObject(AVCaptureDevice);return result;
}// 判断相册权限是否开启
function judgeIosPermissionPhotoLibrary() {var result = false;var PHPhotoLibrary = plus.ios.import("PHPhotoLibrary");var authStatus = PHPhotoLibrary.authorizationStatus();console.log("authStatus:" + authStatus);if (authStatus == 3) {result = true;console.log("相册权限已经开启");} else {console.log("相册权限没有开启");}plus.ios.deleteObject(PHPhotoLibrary);return result;
}// 判断通讯录权限是否开启
function judgeIosPermissionContact() {var result = false;var CNContactStore = plus.ios.import("CNContactStore");var cnAuthStatus = CNContactStore.authorizationStatusForEntityType(0);if (cnAuthStatus == 3) {result = true;console.log("通讯录权限已经开启");} else {console.log("通讯录权限没有开启");}plus.ios.deleteObject(CNContactStore);return result;
}// 判断日历权限是否开启
function judgeIosPermissionCalendar() {var result = false;var EKEventStore = plus.ios.import("EKEventStore");var ekAuthStatus = EKEventStore.authorizationStatusForEntityType(0);if (ekAuthStatus == 3) {result = true;console.log("日历权限已经开启");} else {console.log("日历权限没有开启");}plus.ios.deleteObject(EKEventStore);return result;
}// 判断备忘录权限是否开启
function judgeIosPermissionMemo() {var result = false;var EKEventStore = plus.ios.import("EKEventStore");var ekAuthStatus = EKEventStore.authorizationStatusForEntityType(1);if (ekAuthStatus == 3) {result = true;console.log("备忘录权限已经开启");} else {console.log("备忘录权限没有开启");}plus.ios.deleteObject(EKEventStore);return result;
}// Android权限查询
function requestAndroidPermission(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('已获取的权限:' + grantedPermission);result = 1}for (var i = 0; i < resultObj.deniedPresent.length; i++) {var deniedPresentPermission = resultObj.deniedPresent[i];console.log('拒绝本次申请的权限:' + deniedPresentPermission);result = 0}for (var i = 0; i < resultObj.deniedAlways.length; i++) {var deniedAlwaysPermission = resultObj.deniedAlways[i];console.log('永久拒绝申请的权限:' + deniedAlwaysPermission);result = -1}resolve(result);// 若所需权限被拒绝,则打开APP设置界面,可以在APP设置界面打开相应权限// if (result != 1) {// gotoAppPermissionSetting()// }},function(error) {console.log('申请权限错误:' + error.code + " = " + error.message);resolve({code: error.code,message: error.message});});});
}// 使用一个方法,根据参数判断权限
function judgeIosPermission(permissionID) {if (permissionID == "location") {return judgeIosPermissionLocation()} else if (permissionID == "camera") {return judgeIosPermissionCamera()} else if (permissionID == "photoLibrary") {return judgeIosPermissionPhotoLibrary()} else if (permissionID == "record") {return judgeIosPermissionRecord()} else if (permissionID == "push") {return judgeIosPermissionPush()} else if (permissionID == "contact") {return judgeIosPermissionContact()} else if (permissionID == "calendar") {return judgeIosPermissionCalendar()} else if (permissionID == "memo") {return judgeIosPermissionMemo()}return false;
}// 跳转到**应用**的权限页面
function gotoAppPermissionSetting() {if (isIos) {var UIApplication = plus.ios.import("UIApplication");var application2 = UIApplication.sharedApplication();var NSURL2 = plus.ios.import("NSURL");// var setting2 = NSURL2.URLWithString("prefs:root=LOCATION_SERVICES");		var setting2 = NSURL2.URLWithString("app-settings:");application2.openURL(setting2);plus.ios.deleteObject(setting2);plus.ios.deleteObject(NSURL2);plus.ios.deleteObject(application2);} else {// console.log(plus.device.vendor);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);}
}// 检查系统的设备服务是否开启
// var checkSystemEnableLocation = async function () {
function checkSystemEnableLocation() {if (isIos) {var result = false;var cllocationManger = plus.ios.import("CLLocationManager");var result = cllocationManger.locationServicesEnabled();console.log("系统定位开启:" + result);plus.ios.deleteObject(cllocationManger);return result;} else {var context = plus.android.importClass("android.content.Context");var locationManager = plus.android.importClass("android.location.LocationManager");var main = plus.android.runtimeMainActivity();var mainSvr = main.getSystemService(context.LOCATION_SERVICE);var result = mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER);console.log("系统定位开启:" + result);return result}
}module.exports = {judgeIosPermission: judgeIosPermission,requestAndroidPermission: requestAndroidPermission,checkSystemEnableLocation: checkSystemEnableLocation,gotoAppPermissionSetting: gotoAppPermissionSetting
}

我把这个文件挂载到了全局

// 配置app端用户设置权限设置
import permision from "@/utils/permission.js"
Vue.prototype.$myapppermision = permision

参考网址:

uniapp中获取当前设备的经纬度(定位)-蒲公英云


http://www.ppmy.cn/news/334504.html

相关文章

uni-app概念(新增)

定义组件 easycom 文件夹 components/组件名/组件名.vue 不需要导入可以在页面中直接使用 uni_ modlues/components/组件名/组件名.vue(这种模式也是可以&#xff09;定义组件 .vue文件就是一个组件(vue是一致)组件传参 1.父传子&#xff1a;props1.1父通过属性的方式传…

Python下载新浪微博视频(流式下载)

import requestsprint("开始下载") url https://f.video.weibocdn.com/mMgApeOYlx07CJarSuxq01041200Yve80E010.mp4?labelmp4_720p&template1280x720.25.0&trans_finger1f0da16358befad33323e3a1b7f95fc9&Expires1588682762&ssig1D6G3huIlC&KI…

uni-app Simple

uni-app框架示例&#xff0c;一套代码&#xff0c;同时发行到iOS、Android、H5、小程序等多个平台&#xff0c;请使用手机扫码快速体验uni-app的强大功能。 一个uni-app工程&#xff0c;默认包含如下目录及文件 ┌─components uni-app组件目录 │ └─comp-a.vue 可复用的a组…

uni-app开始

1.编辑器&#xff1a; 1&#xff09;Hbuilder X ----- 下载地址 HBuilderX-高效极客技巧HBuilderX是当前最快的HTML开发工具&#xff0c;强大的代码助手帮你快速完成开发&#xff0c;最全的语法库和浏览器兼容性数据让浏览器碎片化不再头痛https://www.dcloud.io/hbuilderx.…

Oracle 发力 MySQL,MariaDB 成功上市,大规模融资锐减 | 解读数据库的 2022

又一年过去了&#xff0c;生活还在继续&#xff0c;现在是反思去年数据库世界所发生事件的绝佳时机。 链接&#xff1a;https://ottertune.com/blog/2022-databases-retrospective/ 声明&#xff1a;本文为 CSDN 翻译&#xff0c;未经允许禁止转载。 作者 | Andy Pavlo 译者 | …

Uni-app API

Uni-app的各种api&#xff0c;各种功能还是很全面的&#xff0c;而且基于vue用法&#xff0c;本身也带有自己的一套UI系统&#xff0c;代码也能兼容app和小程序&#xff0c;还是挺方便的。 基础 #日志打印 日志打印 向控制台打印日志信息定时器 在定时到期以后执行注…

uni-app上架

材料准备&#xff1a; 1、营业执照或其他主办方证件 2、法人身份证正反面扫描件 3、法人手持身份证正反面照片 4、负责人身份证正反面扫描件 5、负责人手持身份证正反面照片 6、公章照片 7、单位基本信息&#xff1a;单位名称、法定代表人、法定代表人身份证号码、注册资本、成…

ChatGPT这么火,如果ChatGPT滥用或者重度依赖,会怎么样?

目录 绪论 风险 风险1 - 思维能力&#xff1a; 风险2-历史文献&#xff1a; 风险3-舆论问题&#xff1a; 总结 我们都知道&#xff0c;现在最火的就是ChatGPT&#xff0c;各大大厂都在讨论它&#xff0c;马大大也出山讨论它&#xff0c;可想而知&#xff0c;已经火到什么地…