I'm building a map with react-leaflet
and in the first load sometimes most of the tiles aren't visualized as you can see below:
I've gone through several stack overflow question and what I've done is:
index.html
fileuseEffect
that runs on every render and calls the method map.invalidateSize()
taken by the useMap()
hookuseEffect
that runs on first render and calls the method map.invalidateSize()
taken by the useMap()
hookuseMapEvents()
hook and when the maps load run the map.invalidateSize()
method taken by the useMap()
hookWhenever I resize the browser window Leaflet renders all the tiles correctly
Has someone encountered the same problem? How have you solved it?
This is a very common issue we come across while using Leaflet components. I also experienced the same problem with the TileLayer and tried many things, as you listed above.
My solution to this issue was to use useEffect
hook to trigger MapContainer
when it is created. First method to do this is to use whenCreated
on MapContainer
. This one didn't work, because Leaflet Release v4.0.0 removed whenCreated
method. However, they also presented a solution:
Removed whenCreated property from the MapContainer component (a ref callback can be used instead).
Since you didn't share any code snippet or fiddle, here is my solution:
First, you need to add ref
to MapContainer
. It shoul call a useState
set method.
<MapContainer center={[lat, lon]} zoom={13} scrollWheelZoom={false} style={{height: "70vh",width: "90vw"}} ref={setMap}>
<TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"/>
</MapContainer>
Then you should add a useEffect
hook to trigger invalidateSize
method:
const [map, setMap] = useState(null);
useEffect(() => {
if (map) {
console.log("map is being jiggled.");
setInterval(() => {
map.invalidateSize(true);
}, 400);
}
}, [map]);
This workaround provided the desired solution for me. I see your question was posted 2 years ago, you might have found the solution already. But for future reference, I find it beneficial that I post the solution anyway. Happy coding!