uniapp 小程序实时且持续获取定位信息(全局设置一次)(单页面监听定位改变)(不采用定时器)

本篇文章实现了uniapp 微信小程序实时获取定位信息,小程序打开即可持续获取定位信息, 位置更新也会触发相关自定义事件


优点

  1. 只设置一次
  2. 不采用定时器的方式
  3. 无需多个页面调用
  4. 单独页面若想获取当前位置是否变化 可单独设置监听,并调用不同逻辑事件

原理: 

  1. 采用uniapp推出的: uni.onLocationChange(监听实时地理位置变化事件)
  2. 在app.vue中定义一次 且设置监听事件(便于独立页面监测定位改变并调用其他事件)

有关"uni.onLocationChange"的相关内容,不再赘述,详情见官网:uni.onLocationChange(FUNCTION CALLBACK) | uni-app官网uni-app,uniCloud,serverlesshttps://uniapp.dcloud.net.cn/api/location/location-change.html#startlocationupdate    


步骤:

1.1 在app.vue中开启监听位置变化:

<script>
	//import httpApi from '@/utils/httpApi.js' //调用接口 自行修改
	export default {
		globalData: {
			latitude: undefined,
			longitude: undefined,
		},
		
		onLaunch: function() {
			console.log('App Launch')
		},
		onShow: function() {
			console.log('App Show')
			uni.startLocationUpdate({
				success: res => {
					uni.onLocationChange(function(res2) {
						console.log('纬度:' + res2.latitude);
						console.log('经度:' + res2.longitude);
						getApp().globalData.latitude = res2.latitude; //赋值给全局变量 后续子页面需要使用
						getApp().globalData.longitude = res2.longitude;
//httpApi.syncLocation(res2.latitude, res2.longitude).then(); //调用上传位置接口 自行修改
					});
				},
				fail: err => console.error('开启小程序接收位置消息失败:', err),
				complete: msg => console.log('调用开启小程序接收位置消息 API 完成')
			});
		},
		onHide: function() {
			console.log('App Hide')
			uni.stopLocationUpdate();
		},
	}
</script>

1.2 在manifest.json文件源码中做相关配置

        (重要设置"startLocationUpdate"和"onLocationChange"):

"mp-weixin" : {
	"appid" : "", //appid
	"setting" : {
		"urlCheck" : false
	},
	"usingComponents" : true,
	"permission" : {
		"scope.userLocation" : {
			"desc" : "定位" //微信小程序获取location必填
		}
	},
	"requiredPrivateInfos": [
			"getLocation", //使用uni.getlocation才需声明
			"startLocationUpdate", //必要
			"onLocationChange" //必要
		]
},

2.1 在app.vue中设置监听globalData(全局变量)的方法:

methods: {
// 监听全局变量变化
watch: function(variate, method) {
	var obj = this.globalData;
	let val = obj[variate]; // 单独变量来存储原来的值
	Object.defineProperty(obj, variate, {
		configurable: false,
		enumerable: true,
		set: function(value) {
			val = value; // 重新赋值
			method(variate, value); // 执行回调方法
		},
		get: function() {
			// 在其他界面调用getApp().globalData.variate的时候,这里就会执行。
			return val; // 返回当前值
		}
	})
},

2.2 在需要监听的页面的onload设置监听

onLoad() {
    //实时获取当前位置
	getApp().watch('latitude', this.watchLocation);
	getApp().watch('longitude', this.watchLocation);
},

2.3 在页面的methods中设置watchLocation方法(监听globalData数据变化后的回调):

//监听location变化回调
watchLocation: function(name, value) {
	console.log('name==' + name, value);
	if (name == 'latitude') {
		this.latitude = value;
	}
	if (name == 'longitude') {
		this.longitude = value;
	}
},

这样就实现啦,如果本文帮助到你的话 记得点个赞哦~

猜你喜欢

转载自blog.csdn.net/weixin_44805839/article/details/131984957