m13r
m13r

Reputation: 2731

How to resize map in Vue2Leaflet if container was hidden at first

How can I reload a Leaflet map from Vue2Leaflet if it was hidden at first and is then shown (e.g. if hidden by bootstrap collapse element)?

<template>
  <b-container>
    <b-button v-b-toggle="collapse" variant="primary">Show map</b-button>
    <b-collapse id="collapse">
      <div id="map">
        <LMap :zoom=13 :center="[47.413220, -1.219482]">
          <LTileLayer url="http://{s}.tile.osm.org/{z}/{x}/{y}.png"></LTileLayer>
        </LMap>
      </div>
    </b-collapse>
  </b-container>
</template>

<script>
import Vue from 'vue'
import { LMap, LTileLayer } from 'vue2-leaflet'
import BootstrapVue from 'bootstrap-vue'
import 'bootstrap/dist/css/bootstrap.min.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
import 'leaflet/dist/leaflet.css'

Vue.use(BootstrapVue)
...
export default {
  ...
  components: {
    LMap,
    LTileLayer
  }
}
</script>

<style>
div#map {
  height: 300px;
  width: 500px;
}
</style>

Upvotes: 3

Views: 1636

Answers (1)

m13r
m13r

Reputation: 2731

I got it working by using the invalidateSize function from the map object (as suggested by this issue) and using the @shown attribute of the collapse element:

<template>
  <b-container>
    <b-button v-b-toggle="collapse" variant="primary">Show map</b-button>
    <b-collapse @shown="reloadMap()" id="collapse">
      <div id="map">
        <LMap ref="map" ...>
          ...
        </LMap>
      </div>
    </b-collapse>
  </b-container>
</template>

<script>
...
export default {
  ...
  methods: {
    reloadMap: function () {
      this.$refs.map.mapObject.invalidateSize()
    }
  }
}
</script>

Upvotes: 3

Related Questions