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;
}
}
}