uniapp 定位使用

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

uniapp 定位使用

LeHan   2022-10-20 我要评论

前言

业务需要用定位功能,还是持续后台定位的,所以研究了一下,深入浅出好吧,大伙直接复制粘贴拿去用就行!我把他分为在微信小程序和APP中的情况, 先发一波APP的,点赞超过10我就发个微信小程序的。

第一步

在manifest.jsop中复制这段代码,xxx是你自己的信息哦,有了这段代码,前台定位和后台定位权限都可以了。

    "mp-weixin" : {
        "permission" : {
            "scope.userLocation" : {
                "desc" : "xxx"  //描述用来干啥的
            }
        },
        "requiredBackgroundModes" : [ "location" ],
        "requiredPrivateInfos" : [
            "getLocation",
            "onLocationChange",
            "startLocationUpdate",
            "startLocationUpdateBackground"
        ]
    },

第二步

在要用的地方写 , 这个是检测手机定位打开没有的代码

				// #ifdef APP-PLUS
				// 获取是否开启定位
				let system = uni.getSystemInfoSync(); // 获取系统信息
				if (system.platform === 'android') { // 判断平台
					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);
					if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
										var main = plus.android.runtimeMainActivity();
				var Intent = plus.android.importClass('android.content.Intent');
				var Settings = plus.android.importClass('android.provider.Settings');
				var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
				main.startActivity(intent); // 打开系统设置GPS服务页面
					}
				} else if (system.platform === 'ios') {
					var cllocationManger = plus.ios.import("CLLocationManager");
					var enable = cllocationManger.locationServicesEnabled();
					var status = cllocationManger.authorizationStatus();
					plus.ios.deleteObject(cllocationManger);
					console.log("手机系统的定位没有打开");
					uni.showModal({
						title: '提示',
						content: '请打开定位服务功能',
						showCancel: false, // 不显示取消按钮
						success() {
							var UIApplication = plus.ios.import("UIApplication");
							var application2 = UIApplication.sharedApplication();
							var NSURL2 = plus.ios.import("NSURL");
							var setting2 = NSURL2.URLWithString("App-Prefs:root=Privacy&path=LOCATION");
							application2.openURL(setting2);
							plus.ios.deleteObject(setting2);
							plus.ios.deleteObject(NSURL2);
							plus.ios.deleteObject(application2);
						}
					});
				}
				// #endif

第三步

开始拿定位 ,用uni的方法

uni.getLocation({success(res)=>{
                console.log('当前位置的经度:' + res.longitude);
		console.log('当前位置的纬度:' + res.latitude);
		console.log('当前位置的速度:' + res.speed);
                console.log('当前位置的精确度:' + res.accuracy);
}) 

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们