React Leaflet使用MapContainer显示图例

2024-04-09

我正在使用 React leaflet 3.1.0,我想在地图中显示图例。 我为图例构建了一个组件,并传递从 MapContainer whenCreated({setMap}) 获取的地图实例。

地图组件:

import { useState } from 'react';
import { MapContainer, TileLayer } from 'react-leaflet';

import './Map.css';
import Legend from './Legend/Legend';

const INITIAL_MAP_CONFIG = {center: [41.98311,2.82493], zoom: 14}

function Map() {
    const [map, setMap] = useState(null);
   
    return (
        <MapContainer center={INITIAL_MAP_CONFIG.center} zoom={INITIAL_MAP_CONFIG.zoom} scrollWheelZoom={true} whenCreated={setMap}>
            <TileLayer
                attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
                url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />              
            <Legend map={map} /> 
        </MapContainer>  
    )
}

export default Map

图例组件:

import { useEffect } from 'react';
import L from 'leaflet';

function Legend({ 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);
        }
    },[]);
    return null
}

export default Legend

Map CSS:

.leaflet-container {
     width: 100vw;
     height: 100vh;
}

图例CSS:

.info {
    padding: 6px 8px;
    font: 14px/16px Arial, Helvetica, sans-serif;
    background: white;
    border-radius: 5px;
}

.legend {
    text-align: left;
    line-height: 18px;
    color: #555;
}

我没有收到任何错误,但看不到图例。


尝试将地图实例放入依赖项数组中。在第一个渲染图中为空,因此无法将图例添加到地图中。

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;
}

Demo https://codesandbox.io/s/react-leaflet-display-legend-using-mapcontainer-epv9u

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

React Leaflet使用MapContainer显示图例 的相关文章