uniapp uni.getLocation:fail 频繁调用会增加电量损耗

今天使用uniapp开发小程序的时候,在onLoad中调用uni.getLocation(), 调用多次之后它直接给我返回报错信息,说什么高频率调用会导致耗电,如有需要可使用持续定位接口 wx.onLocationChange

然后我就去瞄了一眼微信官方文档

wx.getLocation(Object object) | 微信开放文档

 

 emm, 这可咋整,上才艺。

嘿嘿,它不是说了吗,可以使用wx.onLocationChange(function callback);那这又是啥玩意呢,看下api

 这他喵的怎么越扯越远了,还要结合wx.startLocationUpdate,wx.startLocationUpdateBackground(Object object)

按照说的我们一步步做,先整个js文件命名location.js,创建一个函数。

/**
 * 授权定位
 */
export const authorization = async () => {
	try {
		return await getWxLocation();
	} catch (error) {
		uni.showModal({
			title: '温馨提示',
			content: '获取权限失败,需要获取您的地理位置才能为您提供更好的服务!是否授权获取地理位置?',
			success: (res) => {
				if (res.confirm) {
					handleOpenSettng();
				}
			}
		});
		return;
	}
}

这里看到我使用了自定义函数getWxLocation、handleOpenSettng

/**
 * @description  定位
 */
const getWxLocation = () => {
	// uni.showLoading({
	// 	title: '定位中...'
	// });
	return new Promise((resolve, reject) => {
		console.log("定位中...");
		// 开启定位追踪
		let _locationChangeFn = (res) => {
			resolve(res)
			uni.hideLoading();
			wx.offLocationChange(_locationChangeFn)
		}

		wx.startLocationUpdate({
			success: (res) => {
				console.log("开启定位追踪", res);
				wx.onLocationChange(_locationChangeFn);
			},
			fail: (err) => {
				console.log('获取当前位置失败', err);
				uni.hideLoading();
				reject();
			}
		})
	})
}

按照文档中说的startLocationUpdate开启小程序进去前台时接受定位消息,并结合wx.onLocationChange()监听实时地理位置变化事件,并将结果在返回。

/**
 * 打开设置
 */
const handleOpenSettng = () => {
	wx.openSetting({
		success: (res) => {
			if (res.authSetting["scope.userLocation"]) {
				// 用户同意授权
				authorization();
			}
		}
	})
}

这个函数是在用户获取定位失败时候,打开小程序设置,手动开启定位服务。

如何使用?

将export 的函数 import 进来

import {   authorization } from '@/util/location.js';

        

 完整代码:

/**
 * 解决 wx.getLocation:fail 频繁调用会增加电量损耗
 */
/**
 * 授权定位
 */
export const authorization = async () => {
	try {
		return await getWxLocation();
	} catch (error) {
		uni.showModal({
			title: '温馨提示',
			content: '获取权限失败,需要获取您的地理位置才能为您提供更好的服务!是否授权获取地理位置?',
			success: (res) => {
				if (res.confirm) {
					handleOpenSettng();
				}
			}
		});
		return;
	}
}
/**
 * @description  定位
 */
const getWxLocation = () => {
	// uni.showLoading({
	// 	title: '定位中...'
	// });
	return new Promise((resolve, reject) => {
		console.log("定位中...");
		// 开启定位追踪
		let _locationChangeFn = (res) => {
			resolve(res)
			uni.hideLoading();
			wx.offLocationChange(_locationChangeFn)
		}

		wx.startLocationUpdate({
			success: (res) => {
				console.log("开启定位追踪", res);
				wx.onLocationChange(_locationChangeFn);
			},
			fail: (err) => {
				console.log('获取当前位置失败', err);
				uni.hideLoading();
				reject();
			}
		})
	})
}

/**
 * 打开设置
 */
const handleOpenSettng = () => {
	wx.openSetting({
		success: (res) => {
			if (res.authSetting["scope.userLocation"]) {
				// 用户同意授权
				authorization();
			}
		}
	})
}

猜你喜欢

转载自blog.csdn.net/weixin_38982591/article/details/125896045