uniapp地图map组件改变scale会瞬移回当前map属性绑定的经纬度的解决办法

在这里插入图片描述

1.创建一个地图map的代码

<map id="map" ref="map" class="map" :latitude="latitude" :longitude="longitude" :scale="scale"
	:markers="markers" @regionchange="regionchange" @markertap="markertap">
	<cover-view class="scale-control" v-if="showMapControler">
		<cover-view class="scale-image-warp" @click.stop="scaletap('add')">
			<cover-image class="scale-image" src="@/static/icons/icon_add.png"></cover-image>
		</cover-view>
		<cover-view class="scale-image-warp" @click.stop="scaletap('reduce')">
			<cover-image class="scale-image" src="@/static/icons/icon_reduce.png"></cover-image>
		</cover-view>
	</cover-view>
	<cover-view class="location-control" @click.stop="locationtap" v-if="showMapControler">
		<cover-image class="location-image" src="@/static/icons/icon_location.png"></cover-image>
	</cover-view>
</map>

这个uniapp内置map组件需要传入latitude,longitude和scale属性,以给地图一开始的定位和缩放大小

data() {
		return {
			longitude: 112.865376,
			latitude: 22.922867,
			scale: 17
		}
}

2.手动控制scale大小以放大缩小地图视野时遇到问题

在开发环境js改变scale变量的值控制地图放大缩小没有问题,但实机预览就有问题,点击改变scale变量,地图中心点会跳回一开始给map组件的经纬度坐标,这明显是不能接受的。

methods: {
	// 控制地图放大缩小
	scaletap(type) {
		if (type === 'add') {
			if (this.scale < 20) {
				this.scale += 1;
			}
		} else if (type === 'reduce') {
			if (this.scale > 3) {
				this.scale -= 1;
			}
		}
	}
}

3.为了解决问题,我想到每次移动都获取下当前地图中心位置

获取地图组件上下文

mounted() {
	this.mapObj = uni.createMapContext('map', this);
},

使用getCenterLocation获取当前地图中心位置

// 实时获取视野中心经纬度,以避免改变scale时瞬移到一开始的经纬度
methods: {
	regionchange() {
		this.mapObj.getCenterLocation({
			type: 'gcj02',
			success: (res) => {
				// 赋值当前视野中心
				this.visionCenter.longitude = res.longitude;
				this.visionCenter.latitude = res.latitude;
			},
			fail: (err) => {
				console.log('获取当前地图中心的经纬度失败:', err);
			}
		})
	}
}

在缩放时把map组件的经纬度更新为当前视野的中心经纬度,缩放跳转问题解决

更改缩放方法

// 控制地图放大缩小
scaletap(type) {
	if (type === 'add') {
		if (this.scale < 20) {
			// 定位改为当前视野中心经纬度,避免实机瞬移回原定位
			this.longitude = this.visionCenter.longitude;
			this.latitude = this.visionCenter.latitude;
			this.scale += 1;
		}
	} else if (type === 'reduce') {
		if (this.scale > 3) {
			// 定位改为当前视野中心经纬度,避免实机瞬移回原定位
			this.longitude = this.visionCenter.longitude;
			this.latitude = this.visionCenter.latitude;
			this.scale -= 1;
		}
	}
}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值