Stevan Tosic
Stevan Tosic

Reputation: 7199

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
    };

Upvotes: 1

Views: 21754

Answers (4)

VladoS
VladoS

Reputation: 71

Solutions under didn't work for me. If you use react-leaflet v3 you can use this. One note, hook useMapEvents you need call from children component "MapContainer" it's impotant!

import {useMapEvents} from "react-leaflet";
import {useState} from "react";

function MyComponent() {
    const [zoomLevel, setZoomLevel] = useState(5); // initial zoom level provided for MapContainer
    
    const mapEvents = useMapEvents({
        zoomend: () => {
            setZoomLevel(mapEvents.getZoom());
        },
    });

    console.log(zoomLevel);

    return null
}

function MyMapComponent() {
    return (
        <MapContainer center={[50.5, 30.5]} zoom={5}>
            <MyComponent />
        </MapContainer>
    )
}

Upvotes: 7

Łukasz Żeromski
Łukasz Żeromski

Reputation: 11

I just solved the above problem quite simply. React leaflet provides a nice "onViewportChange" callback that captures center and zoom changes when using the map.

You need three things, the declared "Viewport" object, a function that supports callback and callback.

const viewport = {
center: [49.32707, 19.10041],
zoom: 5,
};

const onViewportChanged = (viewport) => {
console.log(viewport);
};

return (

<Map viewport={viewport} onViewportChanged={onViewportChanged}></Map>)

Best regards

Upvotes: 1

StangSpree
StangSpree

Reputation: 439

This can be alternatively done without using refs. Use the event 'onZoomEnd'.

This event object has '_zoom' property, which is current zoom state.

e.target._zoom

Upvotes: 1

Rodius
Rodius

Reputation: 2311

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();
}

Upvotes: 8

Related Questions