How can I get the current Leaflet map zoom level?
Asked Answered
H

3

14

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}

                    >
Hambley answered 14/1, 2020 at 12:55 Comment(0)
V
21

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()}
Veterinarian answered 14/1, 2020 at 13:0 Comment(3)
I have tried that yet, throws an error. Cannot read property 'getZoom' of undefinedHambley
Try ref={(ref) => { this.mapRef = ref }} instead of ref={this.mapRef}.Veterinarian
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.Veterinarian
P
3

The following code works in JavaScript:

map.on('zoomend', function (e) {
    console.log(e.target._zoom);
});
Prostatectomy answered 15/4, 2023 at 8:58 Comment(2)
In Javascript, developers usually prepend their variable names with an underscore to denote that this is a private variable and it should not be used outside the class scope. So this practice might also be valid here and the _zoom variable isn't meant to be read directly.Craunch
FYI the method you're using here is a jQuery method, not core JS. api.jquery.com/on/#on-events-selector-data-handlerUnapt
R
-1

In react You can get zoomLevel by using getZoom method() and using useRef.

1) const mapRef = useRef(null) 

2) const getMapZoom = () => {
 return mapRef && console.log("object", mapRef.current.getZoom());
 };

 3) <MapContainer
    className="markercluster-map"
    center={center}
    zoom={ZOOM_LEVEL}
    maxZoom={MAX_ZOOM}
    ref={mapRef}
    whenCreated={(mapInstance) => (mapRef.current = mapInstance)}
    whenReady={() => {}}
    >
Redivivus answered 8/12, 2021 at 10:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.