Good morning I know there is a duplicate but the proposed solution does not work, I would like to put a simple Legend with MapContainer, can you give an you give me a hand, to make the legend component with react leaflet 3.x?
Versionn React-Leaflet 3.1.0 This is my map
<MapContainer
style={{ height: 480, width: "97.5%" }}
zoom={2}
center={[30.09, 51.505]}
scrollWheelZoom={false}
fadeAnimation={true}
markerZoomAnimation={true}
>
<TileLayer
url={urlLayer}
test="http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Legend />
<CircleMarker
center={[51.505, -0.09]}
color={"#000000"}
fillColor={"#FDD876"}
stroke={true}
fillOpacity={true}
weight={1}
>
<Popup>
A pretty CSS3 popup. <br /> Easily customizable.
</Popup>
</CircleMarker>
</MapContainer>
I insert whenCreated with hooks of map
const [map, setMap] = useState(null);
<MapContainer
style={{ height: 480, width: "97.5%" }}
zoom={2}
center={[30.09, 51.505]}
scrollWheelZoom={false}
fadeAnimation={true}
markerZoomAnimation={true}
whenCreated={setMap}
>
Legend
import L from "leaflet";
import { useEffect } from "react";
import './LegendComponent.css'
function Legend({ map }) {
console.log(map);
useEffect(() => {
if (map) {
const legend = L.control({ position: "bottomright" });
legend.onAdd = () => {
const div = L.DomUtil.create("div", "info legend");
div.innerHTML =
"<h4>This is the legend</h4>" +
"<b>Lorem ipsum dolor sit amet consectetur adipiscing</b>";
return div;
};
legend.addTo(map);
}
}, [map]); //here add map
return null;
}
export default Legend;
Another way to add a legend in the @Giacomo example, but in a react-leaflet v2 class is:
class Legend extends MapControl {
createLeafletElement(props) { }
componentDidMount() {
const legend = L.control({ position: "bottomleft" })
legend.onAdd = () => {
const QuadroLegenda = L.DomUtil.create("div", "info legend")
let legendas = []
legendas.push(
'<iframe width="750" height="122" src="https://<my_server>/geoserver/<my_city>/wms?REQUEST=GetLegendGraphic&VERSION=1.0.0 \
&FORMAT=image/png&WIDTH=20&HEIGHT=20&LAYER=esgoto \
&LEGEND_OPTIONS=forceRule:True;fontName:Arial;fontAntiAliasing:true;fontColor:0x000000;fontSize:8;columns:6;rows:4;bgColor:0xFFFFFF;borderColor:000000;border:true;dpi:180;dx:0.2;dy:0.2;mx:0.2;my:0.2" frameborder="0"></iframe>'
)
QuadroLegenda.innerHTML = legendas.join()
return QuadroLegenda
}
const { map } = this.props.leaflet
legend.addTo(map)
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.