gpt4 book ai didi

javascript - React-leaflet:添加 TopoJSON 层

转载 作者:行者123 更新时间:2023-12-02 04:00:30 24 4
gpt4 key购买 nike

我刚刚开始使用react-leaflet 库并获得了一个要加载geoJSON 层的 map ,但是我想使用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>
)
}
}

最佳答案

基于provided TopoJSON layer可以为 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>

结果

enter image description here

这是一个live demo

关于javascript - React-leaflet:添加 TopoJSON 层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42149718/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com