0
votes

I have created leaflet map with readily available vue component 'l-map' imported from 'vue2-leaflet. Now I want to recenter the map on button click but I do not know how to gain access to 'map' object (as shown in many examples with functions like 'map.flyTo()', etc) which is used to create map through functions. I tried adding 'center' in @watch property and assign it to 'center' attribute of l-map tag but the map didn't show any changes based on changes in it's value. How can I access map functions when I create it using component from 'vue2-leaflet library??

<template>
<l-map :zoom="zoom" :center="center">
      <v-btn small @click="recenterMap()">
           <span class="mdi mdi-target" />
      </v-btn>
</l-map>
</template>
<script lang="ts">
import { LMap, LControl } from "vue2-leaflet";
import { Component, Vue } from 'vue-property-decorator';

@Component({
 components: {
  LMap,
  LControl
 }
})
export default class MyMap extends Vue {
  center= { lat: 11.016749, lng: 76.955817 };

  recenterMap(){}
}
</script>
2
do you want a dynamic center in the leaflet?SaZa
No. I just want to bring my map view back to where it was when loaded in DOM. (something similar to Re-center button functionality in google maps which brings focus back on device location).Yogesh Vadekar
@YogeshVadekar, Make your question clearer and use properly formatting.NKSM
Ok, So I have attached sample code here. How can I make the map come back to its center on the click of a button when I don't have access to 'map' object as I have created the map with 'LMap' component provided by 'vue2-leaflet' package?Yogesh Vadekar
I tried putting 'center' property under 'Watch' but it reflects only once and then it stops working. Currently changing id of l-map component in template functionally is the workaround I am using. But it might create problem ahead by making more api calls, thus, increasing cost of project.Yogesh Vadekar

2 Answers

3
votes

For getting the original leaflet map you can use that:

<l-map ref="map" :zoom="zoom" :center="center">
    // Your code
</l-map>
mounted() {
   this.$nextTick(() => {
      this.map = this.$refs.map.mapObject;
   });
}

Docu: https://vue2-leaflet.netlify.app/faq/#how-can-i-specify-leaflet-options-that-aren-t-part-of-a-component-s-props

2
votes

You can make a ref to your map component like:

<l-map ref="myMap" :zoom="zoom" :center="center">
      <v-btn small @click="recenterMap()">
           <span class="mdi mdi-target" />
      </v-btn>
</l-map>

and then access the mapObject via reference with a method like

recenterMap() {
   this.$refs.myMap.mapObject.panTo(<your center coordinates object>)
  }