The applet wx.onLocationChange is backward compatible with wx.getLocation

Since the new version of wx.getLocation has a frequency limit, the good location interface can no longer be called frequently. Only the new version of wx.onLocationChange can be used, but the new version of wx.onLocationChange must be above 2.8.1 to be used. In the end, there is no way but to be backward compatible. insert image description here
First, determine the current version number of WeChat. Here, I used the api used to determine the ios model to obtain the version number and store it in the global.

let capsuleObj = wx.getMenuButtonBoundingClientRect();
wx.getSystemInfo({
    
    
      success: (res) => {
    
    
           if(res.platform == "ios" || res.system.indexOf('iOS') > -1 || res.system.indexOf('macOS') > -1){
    
    
             this.globalData.isIos = true;
           }
           // console.log("==获取系统信息==");
           var statusBarHeight = res.statusBarHeight; //顶部状态栏高度
           this.globalData.headerHeight = statusBarHeight + capsuleObj.height + (capsuleObj.top - statusBarHeight) * 2;
           let version = res.SDKVersion; // 获取当前基础库版本号
           this.globalData.version = version.replace(/\./g, ""); //去除点转换为数字来比较大小 
       },
       fail() {
    
    
       }
   })

Then on the page where you get the location

 // 定时获取当前经纬度
    getlocation() {
    
    
        wx.getLocation({
    
    
            type: 'gcj02',
            success: res => {
    
    
                this.data.signInfo.signLongitude = res.longitude;
                this.data.signInfo.signLatitude = res.latitude;
            },
            fail: error => {
    
    
                wx.showModal({
    
    
                    title: '提示',
                    content: '定位失败,请检查是否授权定位',
                    showCancel: false,
                    success:res=> {
    
    
                        this.toSetting();
                    }
                })
            }
        })
        if (this.data.localTimer) {
    
    
            clearInterval(this.data.localTimer)
            this.data.localTimer = null;
        }
        if(app.globalData.version > 2160){
    
    
            // 如果当前微信版本库大于2.17.0调取新接口
            this.data.localTimer = setInterval(() => {
    
    
                this.getWxLocation() //等待
            }, 3000)
        }else {
    
    
        	// 低版本调取老接口
            this.data.localTimer = setInterval(() => {
    
    
                wx.getLocation({
    
    
                    type: 'gcj02',
                    success: res => {
    
    
                        this.data.signInfo.signLongitude = res.longitude;
                        this.data.signInfo.signLatitude = res.latitude;
                      
                    },
                    fail: error => {
    
    
                    }
                })
            }, 3000)
        }
    },
    // 新版获取定位
    getWxLocation() {
    
    
        let that = this;
        try {
    
    
            let _locationChangeFn = (res) => {
    
    
                that.data.signInfo.signLongitude = res.longitude;
                that.data.signInfo.signLatitude = res.latitude;
                wx.offLocationChange(_locationChangeFn) //只监听一次后关闭 
            }
            // 开启小程序进入前台时接收位置消息
            wx.startLocationUpdate({
    
    
                success: (res) => {
    
    
                	// 监听位置信息
                    wx.onLocationChange(_locationChangeFn)
                },
                fail: (err) => {
    
    }
            })
        } catch (error) {
    
    

        }
    },
    //设置去开启定位权限
    toSetting() {
    
    
        let self = this
        wx.openSetting({
    
    
            success(res) {
    
    
                if (res.authSetting["scope.userLocation"]) {
    
    
                    // res.authSetting["scope.userLocation"]为trueb表示用户已同意获得定位信息,此时调用getlocation可以拿到信息
                }
            }
        })
    },
    

Finally don't forget to turn off the timer when destroying the page

  onUnload: function () {
    
    
        if (this.data.localTimer) {
    
    
            clearInterval(this.data.localTimer);
            this.data.localTimer = null;
        }
    },

2023.5.7 Modification

Append encapsulation method

getloaction.js

const getLoactionFunc = function(version = 800) {
    
    
	return new Promise((resolve, reject) => {
    
    
		if (version > 2160) {
    
    
			// 如果当前微信版本库大于2.17.0调取新接口
			try {
    
    
				let _locationChangeFn = (res) => {
    
    
					wx.offLocationChange(_locationChangeFn) //只监听一次后关闭 
					wx.stopLocationUpdate(_locationChangeFn)
					console.log("获取新版定位", res)
					resolve(res)
				}
				// 开启小程序进入前台时接收位置消息
				wx.startLocationUpdate({
    
    
					type: 'gcj02',
					success: (res) => {
    
    
						// 监听位置信息
						wx.onLocationChange(_locationChangeFn)
					},
					fail: (err) => {
    
    }
				})
			} catch (error) {
    
    
				reject(error)
			}
		} else {
    
    
			// 低版本调取老接口
			wx.getLocation({
    
    
				type: 'gcj02',
				success: res => {
    
    
					console.log("获取老版定位", res)
					resolve(res)
				},
				fail: () => {
    
    
					reject(error)
				}
			});
		}
	})
}
export default getLoactionFunc

You only need to call the required page reference

import getLoactionFunc from "@/utils/getloaction.js"

// 注意传全局获取的微信基础库版本号
getLoactionFunc(this.data.version).then(res=>{
    
    
	this.data.latitude = res.latitude;
	this.data.longitude = res.longitude;
})

Guess you like

Origin blog.csdn.net/weixin_38566069/article/details/122989053