Solve the problem that the center point is biased to the upper left corner after the map in the modal box is opened

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

In the above code, we set Beijing as the center point of the map, but when we open the modal box, we will find that Beijing is biased to the upper left corner, as shown in the following figure:

The reason for this problem is that the map initialization is carried out in the mounted life cycle, that is to say, the map is loaded before the modal box is opened, and the width and height of the modal box are 0 at this time, so the center point of the map is will appear in the upper left corner.

So we need to wait for the modal box to open, and then load the map with the width and height:

Therefore, the initMap method cannot be executed in the mounted life cycle, but should be executed after the modal box is opened. At the same time, it should be noted that setTimeout should be used for asynchronous loading:

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

Full code:

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

At this point, the center point of the map can be displayed in the center:

Guess you like

Origin blog.csdn.net/lq313131/article/details/128827175