繁体   English   中英

react-leaflet:添加 TopoJSON 层

[英]react-leaflet: adding a TopoJSON layer

我刚开始使用 react-leaflet 库,并得到了一张地图来加载 geoJSON 层,但是我想改用 TopoJSON 层。

我知道像这样的纯传单是可能的: https ://gist.github.com/rclark/5779673/。

但是我将如何使用 React-Leaflet 来做到这一点?

编辑

class MapViz extends React.Component {

    getStyle() {...};

    render() {
        const position = [x,y];
        var geoData = topojson.feature(test_topo,test_topo.objects).geometries;
        return (
            <Map id="my-map" center={position} zoom={10.2}>
                <TileLayer ... />
                <GeoJSON data={geoData} style={this.getStyle} />
            </Map>
        )
    }
}

基于提供的 TopoJSON 层,可以为react-leaflet库引入以下用于呈现 TopoJSON 的组件

import React, { useRef, useEffect } from "react";
import { GeoJSON, withLeaflet } from "react-leaflet";
import * as topojson from "topojson-client";

function TopoJSON(props) {
  const layerRef = useRef(null);
  const { data, ...defProps } = props;

  function addData(layer, jsonData) {
    if (jsonData.type === "Topology") {
      for (let key in jsonData.objects) {
        let geojson = topojson.feature(jsonData, jsonData.objects[key]);
        layer.addData(geojson);
      }
    } else {
      layer.addData(jsonData);
    }
  }

  useEffect(() => {
    const layer = layerRef.current.leafletElement;
    addData(layer, props.data);
  }, []);

  return <GeoJSON ref={layerRef} {...defProps} />;
}

export default withLeaflet(TopoJSON);

笔记:

用法

<Map center={[37.2756537,-104.6561154]} zoom={5}>
    <TileLayer
      attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
      url="https://{s}.tile.osm.org/{z}/{x}/{y}.png"
    />
     <TopoJSON
      data={data}
      />
</Map>

结果

在此处输入图像描述

这是一个现场演示

它与您链接的要点非常相似。 您需要将 TopoJSON 转换为 GeoJSON,并像通常使用 GeoJSON 一样设置数据。 它可以在你的渲染方法中

 import topojson from 'topojson';
 ....
 ....


render() {
  geoData = topojson.feature(topoData,topoData.objects).features;

  return (
    <LeafletMap>
      <GeoJson
        data={geoData}
      />
     </LeafletMap>
  ) 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM