解决模态框中的地图打开后中心点偏向左上角的问题

<template>
  <div>
    <button @click="mapModal=true">打开地图模态框</button>
    <Modal
      class="modal"
      width='60%'
      v-model="mapModal"
      :mask-closable='false'
      >
      <div id = "container"></div>
    </Modal>
  </div>
</template>

<script>
export default {
  data(){
    return {
      mapModal: false,
      map: null
    }
  },
  methods:{
    initMap(){
      this.map = new BMapGL.Map("container", {enableMapClick:false}); // 创建Map实例,GL版命名空间为BMapGL(鼠标右键控制倾斜角度)
        this.map.centerAndZoom(new BMapGL.Point(116.404, 39.915), 11);      // 初始化地图,设置中心点坐标和地图级别
      this.map.enableScrollWheelZoom(true);                               // 开启鼠标滚轮缩放
    }
  },
  mounted(){
    this.initMap()
  }
}
</script>

<style>
button{
  margin-left: 320px;
}
#container{
  width: 100%;
  height: 450px;
}
</style>

上述代码我们设置了北京为地图的中心点,但是当我们打开模态框时会发现北京偏向了左上角,如下图所示:

出现这个问题的原因是地图初始化是在mounted生命周期进行的,也就是说模态框还没有被打开就加载好地图了,而此时模态框的宽高是0,因此地图的中心点就会出现在左上角。

因此我们需要等模态框打开后,有了宽高再去加载地图:

所以initMap方法不能在mounted生命周期去执行,而要在模态框打开后再去执行,同时要注意要使用setTimeout进行异步加载:

mapOpen(){
  this.mapModal = true
  setTimeout(()=>{
    this.initMap()
  })
},

完整代码:

<template>
  <div>
    <button @click="mapOpen">打开地图模态框</button>
    <Modal
      class="modal"
      width='60%'
      v-model="mapModal"
      :mask-closable='false'
      >
      <div id = "container"></div>
    </Modal>
  </div>
</template>

<script>
export default {
  data(){
    return {
      mapModal: false,
      map: null
    }
  },
  methods:{
    mapOpen(){
      this.mapModal = true
      setTimeout(()=>{
        this.initMap()
      })
    },
    initMap(){
      this.map = new BMapGL.Map("container", {enableMapClick:false}); // 创建Map实例,GL版命名空间为BMapGL(鼠标右键控制倾斜角度)
        this.map.centerAndZoom(new BMapGL.Point(116.404, 39.915), 11);      // 初始化地图,设置中心点坐标和地图级别
      this.map.enableScrollWheelZoom(true);                               // 开启鼠标滚轮缩放
    }
  },
  mounted(){
    // this.initMap()
  }
}
</script>

<style>
button{
  margin-left: 320px;
}
#container{
  width: 100%;
  height: 450px;
}
</style>

此时就可以让地图中心点显示在中心了:

猜你喜欢

转载自blog.csdn.net/lq313131/article/details/128827175
今日推荐