React-leaflet:添加 TopoJSON 层

2024-01-29

我刚刚开始使用 React-leaflet 库并获得了一个要加载 geoJSON 层的地图,但是我想使用 TopoJSON 层。

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

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

Edit

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层 https://gist.github.com/rclark/5779673/可以引入以下用于渲染 TopoJSON 的组件react-leaflet library

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

Notes:

  • 它延伸GeoJSON成分 https://react-leaflet.js.org/docs/en/components#geojson from react-leaflet library
  • 有依赖性topojson-client https://www.npmjs.com/package/topojson-client它提供了用于操作 TopoJSON 的工具

Usage

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

Result

这里有一个现场演示 https://stackblitz.com/edit/react-nogiq8

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

React-leaflet:添加 TopoJSON 层 的相关文章