0

I am trying to get top left and right bottom of the Map which i am displaying. And i am trying to get this particular data in zoom event, but somehow this.map is becoming undefined and breaking the application

 this.map.on('zoomend', function (layer) {
      console.log("zoom",layer.target._zoom)
      console.log("getbounds", this.map.getBounds());
      });

Below i am providing the componentDidMount, here only i am defining zoom event, which working fine if i simply console.

 componentDidMount() {

        /* We are loading the map here whether or not load has loaded */
        this.map = L.map('map', {
            center: [50, 10],
            zoom: 3,
            minZoom: 2,
            maxZoom: 11,
            zoomControl: false,
            attributionControl: false,
            scrollwheel: false,
            legends: true,
            infoControl: false,
        });
        console.log("getbounds", this.map.getBounds()); //WORKING BUT JUST ONCE, when this component mounts.

        this.map.on('zoomend', function (layer,a) {
            console.log("zoom",layer.target._zoom)
            console.log("zoom",layer)
            console.log("a",a)
            console.log("getbounds", this.map.getBounds()); // NOT WORKING, this.map GETS UNDEFINED which is obvious also.
        });


        /* Giving zoom control a  different place in UI */
        L.control.zoom({ position: 'topright' }).addTo(this.map);
        L.control.scale({ position: "topright" }).addTo(this.map);

        /* Selecting and showing styles for the map */
        L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}', {
        }).addTo(this.map);
}
TrickOrTreat
  • 821
  • 1
  • 9
  • 23

1 Answers1

0

Just change this part of your code bro

this.map.on('zoomend', (layer,a) => {
            console.log("zoom",layer.target._zoom)
            console.log("zoom",layer)
            console.log("a",a)
            console.log("getbounds", this.map.getBounds()); // NOT WORKING, this.map GETS UNDEFINED which is obvious also.
        });

The reason why your code did not work is you were using simple function as a callback which need to bind to use this. Solution: Use arrow function

Dostonbek Oripjonov
  • 1,508
  • 1
  • 12
  • 28