How can I get the current Leaflet map zoom level?

12,481

In pure leaflet if you defined map as const map = L.map("map", options) than you just call map.getZoom().

In constructor this.mapRef = React.createRef() In Map element:

    ref={this.mapRef}
    onzoomend={() => console.log(this.mapRef.current.leafletElement.getZoom()}
Share:
12,481

Related videos on Youtube

ODLana
Author by

ODLana

Updated on June 04, 2022

Comments

  • ODLana
    ODLana 7 months

    I'm trying to get the zoom level of a map in real time to make a button that locks the zoom with the current value. I have tried using getMapZoom and getZoom but both give me an undefined value. I think I'm not using the correct ref but I haven't been able to find much documentation about it. Here's the code:

    <Map className="map-layer" 
              center={center} 
              onoverlayadd={this.overlayadd} 
              onoverlayremove={this.overlayremove}
              ondragend={this.zoomChange}
              onzoomend={console.log('Zoom: ' + this.mapRef.leafletElement.getMapZoom())}
              zoom={this.state.zoom}
              ref={this.mapRef}
              preferCanvas={false}
              animate={true}
              scrollWheelZoom={this.state.zoomLock ? false : true}
              doubleClickZoom={this.state.zoomLock ? false : true}
              touchZoom={this.state.zoomLock ? false : true}
              maxZoom={7}
              minZoom={7}
                        >
    
  • ODLana
    ODLana almost 3 years
    I have tried that yet, throws an error. Cannot read property 'getZoom' of undefined
  • radulle
    radulle almost 3 years
    Try ref={(ref) => { this.mapRef = ref }} instead of ref={this.mapRef}.
  • radulle
    radulle almost 3 years
    I haven't noticed you weren't passing the function to the onzoomend. I updated the answer. You should pass functions to other onevent handlers too.

Related