【uniapp 小程序】解决 map 组件出现标点(地图)自动偏移或 @regionchange 频繁触发的问题

【uniapp / 小程序】解决 map 组件出现标点(地图)自动偏移或 @regionchange 频繁触发的问题

在业务开发中出现了地图的中心标点向右侧缓慢移动的问题,在我解决后又发现了 @regionchange 方法出现了无限调用的问题。这几个问题属于微信 map 地图组件迟迟未修复的bug。

本文仅解决与我相似的问题以做参考,并会附上对应的问题与参考的博客。

一、问题复现

1、地图无操作下出现缓慢的自行移动:

original-original

2、无触发下提示信息被一直触发:

original-original-1

3、相关的问题代码

	
		
			
	

  • scale:缩放
  • circles:区域圆
  • latitude\longitude:地图中心坐标
  • markers:标点
  • show-location:带箭头的当前坐标
  • regionchange:视角移动切换时触发
  • callouttap:点击标点事件
  • tap:点击地图触发事件
changeRegion(e) { //中心点标记始终在地图中心位置不动
	let that = this;
	this.mapCtx = uni.createMapContext('map');
	this.mapCtx.getCenterLocation({
		success(res) {
			const latitude = res.latitude
			const longitude = res.longitude
             console.log(latitude, longitude);
			console.log(that.lat, that.lng);
			that.lat = latitude
			that.lng = longitude
			if (that.scrollTimer) {
				clearTimeout(that.scrollTimer);
			}
			that.scrollTimer = setTimeout(() => {
				that.latitude = res.latitude;
				that.longitude = res.longitude;
				that.getMapHouses(res.longitude, res.latitude); // 请求区域内存在数据
			}, 1500)
		}
	})
},

二、问题解决

主要问题存在于 @regionchange 方法不断被触发,且不移动时获取的维度坐标总比我们当前的 -1 。

image-20231116151207139

解决代码:

通过限制静态时触发的偏移量,不触发对应的区域接口,各位的数据偏移量和方向可能各有不同,需要根据具体的问题进行设置。

changeRegion(e) { //中心点标记始终在地图中心位置不动
	console.log(e);
	let that = this;
	if (e.type == 'end') { // 仅获取结束坐标
		this.mapCtx = uni.createMapContext('map');
		this.mapCtx.getCenterLocation({
			success(res) {
				const latitude = res.latitude
				const longitude = res.longitude

				if ((that.lng - longitude)  0 &&
					latitude == that.lat) { // 对静态移动标点做限制防止偏移
					return
				}
				if (that.scrollTimer) { // 设置节流,进一步限制高频触发
					clearTimeout(that.scrollTimer);
				}
				that.scrollTimer = setTimeout(() => {
					that.lat = latitude
					that.lng = longitude
					that.latitude = res.latitude;
					that.longitude = res.longitude;
					that.getMapHouses(res.longitude, res.latitude); // 请求区域内存在数据
				}, 1500)
			}
		})
	} else { // begin
	}
},

参考文献:

  1. 微信小程序–地图regionchange事件频繁触发导致崩溃-CSDN博客
  2. 微信小程序 地图定位、选址,解决regionchange重复调用-CSDN博客
  3. 微信小程序 地图定位、选址,解决regionchange重复调用-CSDN博客
  4. Map 组件在开发者工具中一直自己移动,真机正常 | 微信开放社区 (qq.com)

本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://net2asp.com/3170161993.html