Search code examples
javascriptreactjsleafletreact-leaflet

How to get Map object in react-leaflet on zoom change event


I am using react-leaflet for showing non-geographical map. I also added some event for zoom changing. (onZoomEnd())

I wonder how to access map object or map component and get current zoom level. Or other maps props?

  <Map
                center={this.getCalculatedCenterFromState()}
                zoom={this.getCalculatedZoomFromState()}
                minZoom={this.getCalculatedMinZoomFromState()}
                maxZoom={2}
                onZoomEnd={this.mapService.handleZoomstart(/* map.object */)}


               >
</Map

I need to access map object in handler method

handleZoomstart = (map) => {
        // TODO handle move event
    };

Solution

  • You need to add a reference to the map:

    <Map
      ref={(ref) => { this.map = ref; }}
      {...}
    >
    (...)
    </Map>
    

    Then you can access the map:

    handleZoomstart = (map) => {
      console.log(this.map && this.map.leafletElement);
    };
    

    And the current zoom:

    getMapZoom() {
       return this.map && this.map.leafletElement.getZoom();
    }