I'm using react-leaflet in one of my projects and I want to show only one country and delete the rest or hide.
Someone has solved this problem but unfortunately it's not for React. Do you know how to turn this into a react code or use it in a react project?
Install the library and import it:
import "leaflet-boundary-canvas";
After retrieving the map instance create a useEffect
that will fetch the example's geojson
having the map in the dependency array. Copy paste the code. The only difference here is that you have to use L.TileLayer.boundaryCanvas
instead of new L.TileLayer.BoundaryCanvas
to initialize the plugin
...
const [map, setMap] = useState(null);
useEffect(() => {
if (!map) return;
const fetchGeoJSON = async () => {
const response = await fetch(
"https://cdn.rawgit.com/johan/world.geo.json/34c96bba/countries/GBR.geo.json"
);
const geoJSON = await response.json();
const osm = L.TileLayer.boundaryCanvas(
"https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
{
boundary: geoJSON,
attribution:
'© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors, UK shape <a href="https://github.com/johan/world.geo.json">johan/word.geo.json</a>'
}
);
map.addLayer(osm);
const ukLayer = L.geoJSON(geoJSON);
map.fitBounds(ukLayer.getBounds());
};
fetchGeoJSON();
}, [map]);
return (
<MapContainer
...
whenCreated={setMap}
/>
);