uniapp uses uni's own map (Tencent Map) to develop the delivery function---locate the delivery person's location in real time in the background

1. Add the following configuration to configuration---manifest.json/source code view/"mp-weixin"

Define a variable globally to indicate the identifier of turning on the background positioning function --- Define positionTimer in main.js

"permission" : {
            "scope.userLocation" : {
                "desc" : "获取配送地址"
            }
        },
        "requiredPrivateInfos" : [
            "getLocation",
            "chooseLocation",
            "onLocationChange",
            "startLocationUpdate",
            "startLocationUpdateBackground"
        ],
        "requiredBackgroundModes" : [ "location" ], //需要再后台使用

 2. Call where a delivery person is needed to grab an order

	//确认抢单
			sureOrderBtn() {
				var that = this;
                 //开启后台小程序也定位功能
				wx.startLocationUpdateBackground({
						if (Vue.prototype.positionTimer == null) {
			            wx.startLocationUpdateBackground({
				                   success(res) {
					Vue.prototype.positionTimer = setInterval(function() {
						let data = {
							lat: '',
							lng: ''
						}
						const _locationChangeFn = function(res) {
							data.lat = res.latitude;
								data.lng = res.longitude

							console.log('这里调用向后端发送经纬度的接口',data)
							wx.offLocationChange(_locationChangeFn)
						}
						wx.onLocationChange(_locationChangeFn)

					}, 30000)
				},
				fail(res) {
					console.log('开启后台定位失败', res);
					//授权失败后引导用户打开定位信息
					this.openSetting();
				}
			})

		}
					},
					fail(res) {
						console.log('开启后台定位失败', res);
						//授权失败后引导用户打开定位信息
						this.openSetting();
					}
				});

			},
//定位授权弹框

openSetting(){
	wx.getSetting({
			success: function(res) {
				var statu = res.authSetting;
				if (!statu["scope.userLocationBackground"]) {
					wx.showModal({
						title: "请授权使用期间和离开后的位置!",
						content: "需要获取您的地理位置,请确认授权,否则地图功能将无法使用",
						success: function(tip) {
							if (tip.confirm) {
								wx.openSetting({
									success: function(data) {
										if (data.authSetting[
												"scope.userLocationBackground"
											] === true) {

										}
									}
								});
							} else {
								//console.log('用户拒绝打开设置界面')
							}
						}
					});
				}
			}
		});
}

Note: After the mini program exits the background, the positioning function can still send the latitude and longitude to the backend normally, but if you kill the mini program, it will not be called again. Therefore: you can determine whether there are items being delivered when you open the mini program. , if there is, the method in sureOrderBtn will be automatically called again.

Guess you like

Origin blog.csdn.net/weixin_69666355/article/details/131327346