【问题标题】:Add zipped shapefiles to a react-leaflet map将压缩的 shapefile 添加到 react-leaflet 地图
【发布时间】:2020-07-30 06:53:21
【问题描述】:

我想将压缩文件夹中的 shapefile 添加到反应传单地图。我尝试将它们转换为 JSON 格式并使用此包读取它们 => https://www.npmjs.com/package/react-leaflet-shapefile 我没有收到任何错误,但地图上没有显示任何内容。但是,当我将 JSON 文件上传到 https://mapshaper.org/ 时,形状是可见的。

【问题讨论】:

    标签: shapefile react-leaflet


    【解决方案1】:

    您可以使用 shpjs 库制作自己的 react-leaflet 组件,以使用 React 和 Leaflet 加载 shapefile。

    使用npm i shpjs --save安装shpjs

    然后创建Shapefile comp:

    ...
    import { useLeaflet } from "react-leaflet";
    import L from "leaflet";
    import shp from "shpjs";
    
    function Shapefile({ zipUrl }) {
      const { map } = useLeaflet();
    
      useEffect(() => {
        const geo = L.geoJson(
          { features: [] },
          {
            onEachFeature: function popUp(f, l) {
              var out = [];
              if (f.properties) {
                for (var key in f.properties) {
                  out.push(key + ": " + f.properties[key]);
                }
                l.bindPopup(out.join("<br />"));
              }
            }
          }
        ).addTo(map);
    
        shp(zipUrl).then(function (data) {
          geo.addData(data);
        });
      }, []);
    
      return null;
    }
    

    然后像孩子一样在 react-leaflet 的 Map 组件上使用它:

     ...
     import zipUrl from "./TM_WORLD_BORDERS_SIMPL-0.3.zip";
     import Shapefile from "./Shapefile";
      ...
    
    <Map center={position} zoom={13} style={{ height: "100vh" }} ref={mapRef}>
          <TileLayer
            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          />
          <Shapefile zipUrl={zipUrl} />
        </Map>
    

    Demo

    【讨论】:

    • 我不明白您是如何设法解压缩/读取 zip 文件以对其进行处理的...另外,您能否在演示中添加一个上传按钮以选择哪个 zip 文件你要治疗吗?
    • 这解决了最初的问题,但除非您的 shapefile 发生变化,否则最好将 shapefile 一次转换为 GeoJSON 并使用 GeoJSON,因为此解决方案每次都在运行时进行转换。
    猜你喜欢
    • 2022-07-06
    • 2020-01-04
    • 1970-01-01
    • 1970-01-01
    • 2015-05-27
    • 2016-02-27
    • 1970-01-01
    • 2014-01-26
    • 2014-10-10
    相关资源
    最近更新 更多