The uniapp applet obtains location information in real time and continuously (set once globally) (monitor location changes on a single page) (does not use a timer)

This article implements the uniapp WeChat applet to obtain location information in real time. The location information can be obtained continuously when the applet is opened, and the location update will also trigger related custom events.


advantage

  1. set only once
  2. without a timer
  3. No need for multiple page calls
  4. If you want to know whether the current location has changed on a separate page, you can set the monitor separately and call different logic events

principle: 

  1. Launched by uniapp:  uni.onLocationChange (monitor real-time location change events)
  2. Define it once in app.vue and set the listening event (to facilitate independent page monitoring of positioning changes and calling other events)

For the relevant content of " uni.onLocationChange ", please refer to the official website for details: uni.onLocationChange(FUNCTION CALLBACK) | uni-app official website uni-app, uniCloud, serverless https://uniapp.dcloud.net.cn/api /location/location-change.html#startlocationupdate    


step:

1.1 Turn on monitoring position changes in 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 Do relevant configuration in the manifest.json file source code

        (important settings "startLocationUpdate" and "onLocationChange"):

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

2.1 Set the method of monitoring globalData (global variable) in app.vue:

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 Set up monitoring on the onload of the page that needs to be monitored

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

2.3 Set the watchLocation method in the methods of the page (the callback after monitoring the globalData data change):

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

That's it, if this article helps you, remember to give it a thumbs up~

Guess you like

Origin blog.csdn.net/weixin_44805839/article/details/131984957