首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用MapContainer显示React Leaflet图例

使用MapContainer显示React Leaflet图例
EN

Stack Overflow用户
提问于 2021-02-15 23:42:08
回答 1查看 624关注 0票数 1

我正在使用React leaflet 3.1.0,我想在地图上显示一个图例。我为从MapContainer whenCreated({setMap})获得的图例和通过图实例构建了一个组件。

Map组件:

代码语言:javascript
复制
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

图例组件:

代码语言:javascript
复制
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

映射CSS:

代码语言:javascript
复制
.leaflet-container {
     width: 100vw;
     height: 100vh;
}

图例CSS:

代码语言:javascript
复制
.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;
}

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-16 00:11:48

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

代码语言:javascript
复制
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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66210996

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档