When I click the button "Search heritage", I want to display the map on my webpage. However, the Leaflet Map cannot show properly as below:
The map can be fully displayed without any problem once I resize my webpage. I have found some solutions that can solve this problem based on class component but I have no idea to solve it when using functional component.
Here is my current code.
import "./leaflet.css";
import { MapContainer, TileLayer, useMap, Popup, Marker } from "react-leaflet";
export default function Leaflet() {
const mapRef: any = createRef();
useEffect(() => {
const map = mapRef.leafletElement;
setTimeout(() => {
map.invalidateSize();
}, 1000);
}, [mapRef]);
return (
<div className="map">
<MapContainer
center={[22.3193, 114.1694]}
zoom={10}
scrollWheelZoom={false}
ref={mapRef}
>
<TileLayer
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={[50.5, 30.5]}>
<Popup></Popup>
</Marker>
</MapContainer>
</div>
);
}
2.leaflet.css
font-family: sans-serif;
text-align: center;
}
.leaflet-container {
height: 600px;
width: 100%;
}
.leaflet-div-icon {
background: transparent;
border: none;
}
I am using react-leaflet ^4.0.0