How do you call fitBounds() when using leaflet-react?

后端 未结 2 872
暗喜
暗喜 2020-12-16 01:12

I cannot figure out how to call fitBounds() on the Leaflet map.

If I was just using vanilla leaflet, this solution would work perfectly: Zoom to fit all markers in M

2条回答
  •  猫巷女王i
    2020-12-16 01:42

    If you want this behavior on map load, you can use the onlayeradd event.

    Example:

    const fitToCustomLayer = () => {
        if (mapRef.current && customAreaRef.current) { //we will get inside just once when loading
            const map = mapRef.current.leafletElement
            const layer = customAreaRef.current.leafletElement
            map.fitBounds(layer.getBounds().pad(0.5))
        }
    }
    
    return (
    
        
            
                
            
            
                
                        
        
    
    )
    

    *Edit: If the ref layer is the last one, this doens't seems to work. Putting it before the base layers doesn't affect the rendering and it works.

    If you need to use the onlayeradd for it's rightful purpose, make sure to add another flag to avoid getting inside the if and firing fitBounds again and lose map's current position.

    Ps: I tried the onload method of react-leaflet, but it doesn't seems to work.

提交回复
热议问题