react-leaflet:添加一个TopoJSON层 [英] react-leaflet: adding a TopoJSON layer

查看:83
本文介绍了react-leaflet:添加一个TopoJSON层的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用react-leaflet库,并获得了要加载geoJSON图层的地图,但是我想改用TopoJSON图层.

我知道使用纯Leaflet可能是这样的:

这是一个实时演示

I just started using the react-leaflet library and got a map to load with a geoJSON layer, however I would like to use a TopoJSON layer instead.

I know that it is possible with pure Leaflet like this: https://gist.github.com/rclark/5779673/.

But how would I go about doing this with 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>
        )
    }
}

解决方案

Based on the provided TopoJSON layer the following component for rendering TopoJSON could be introduced for 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:

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

Here is a live demo

这篇关于react-leaflet:添加一个TopoJSON层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆