【问题标题】:How to create a legend from geojson data with react-leaflet如何使用 react-leaflet 从 geojson 数据创建图例
【发布时间】:2021-10-18 09:56:37
【问题描述】:

我的地图中显示了一些数据,我想创建一个图例,该图例与我的数据和名称具有相同的图像。 我的数据是 Geojson 文件。

我的地图是这样的:

没有图例的地图

我想发展一个这样的传奇:

带图例的地图

这是我向地图表示数据的代码:

import React from "react";
import L from "leaflet";
import {
   MapContainer,
   TileLayer,
   GeoJSON,
   Marker,
   Popup,
   LayersControl,
} from "react-leaflet";

import noeud from "./../data/Noeud.json";
import section from "./../data/section.json";
import casier from "./../data/casier.json";

function Macarte() {

  const noeud_icon = L.icon({
  iconUrl: noeud_image,
  iconSize: [10, 10],
 });

 function casier_style() {
    return {
      fillColor: "transparent",
      color: "red",
   };
  }

 function section_style() {
   return {
      color: "black",
   };
 }

 return (
    <MapContainer className="map" center={[45.7133, 5.52826]} zoom={11}>
    <LayersControl position="topright" />
    <TileLayer
     attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
     url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
    />

   {noeud.features.map((data_noeud) => (
    <Marker
      icon={noeud_icon}
      position={{
        lat: data_noeud.geometry.coordinates[1],
        lng: data_noeud.geometry.coordinates[0],
      }}
    >
      <Popup>
        <div>
          {/*<h1> {"Nom modèle : " + data_noeud.properties.Nom_modele} </h1>*/}
          <h1> {"Noeud : " + data_noeud.properties.NOM} </h1>
        </div>
      </Popup>
    </Marker>
  ))}

  <GeoJSON
    style={section_style}
    data={section.features}
  />

 <GeoJSON
    style={casier_style}
    data={casier.features}
  />
 </MapContainer>

 );
 }


 export default Macarte;

请帮忙:)

【问题讨论】:

    标签: legend geojson react-leaflet


    【解决方案1】:

    here 已经回答了类似的问题。 图例组件

    function Legend({ map }) {
      console.log(map);
      useEffect(() => {
        if (map) {
          const legend = L.control({ position: "bottomright" });
          legend.onAdd = () => {
            const div = L.DomUtil.create("div", "legend");
            div.innerHTML =
              "<h4>Legend</h4>"
            return div;
          };
    
          legend.addTo(map);
        }
      }, [map]); //here add map
      return null;
    }
    

    在 .css 文件中,您可以为图例建立规则,然后将其导入到您的图例组件中。

    .legend {
       padding: 6px 8px;
       font: 14px Arial, Helvetica, sans-serif;
       background: rgb(255, 255, 255);
       line-height: 24px;
       color: rgb(0,0,0)
    }
    
    .legend h4 {
       text-align: center;
       font-size: 16px;
       margin: 2px 12px 8px;
       color: rgb(0,0,0)
    }
    

    然后您可以简单地将 Legend 组件放在您想要的任何位置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-11
      • 1970-01-01
      • 1970-01-01
      • 2020-10-02
      • 1970-01-01
      相关资源
      最近更新 更多