1

I need to know when the bounding box of the Leaflet map changes after the move and zoom process. I need to access it in componentDidUpdate. I have tried the code below but it doesn't work.

This is my code.

class Map extends Component {
    constructor(props) {
        super(props)
        this.state= {
            map: null,
            bbox: null
        }
    }

    setupLeafletMap() {
        const position = [-2.6000285, 118.015776]
        const zoom = 5
        let map = L.map('map', {
            center: position,
            zoom: zoom
        })
        
        this.setState({map})

        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            minZoom: 2,
            maxZoom:18
        }).addTo(map)

        map.on('moveend', function() { 
            const bounds = map.getBounds()
            this.setState({
                bbox: bounds
            });
        });
        

        map.on('zoomend', function() { 
            const bounds = map.getBounds()
            this.setState({
                bbox: bounds
            });            
        });
    }

    componentDidMount() {
        this.setupLeafletMap()
    }

    componentDidUpdate(prevState) {
        if(prevState.bbox !== this.state.bbox) {
             // do something
        }
    }

    render() {
        return (
        <div id="map"></div>
        )
    }
}

Does anyone have a solution for this problem? Or how can I access Leaflet events such as zoomend and moveend in componentDidUpdate?

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.