如何在d3中显示json而不是React中的leaflet.js



我正在努力显示一些json数据到我的传单地图在反应。我使用leaflet-react来运行地图生成。我找不到一个像样的教程来帮助我解决这个问题。我的当前设置如下;

const MapComponent = () => {
return (
<>
<MapContainer
center={[mapSettings.latitude, mapSettings.longitude]}
zoom={mapSettings.zoom}
minZoom={6}
scrollWheelZoom={true}
zoomControl={false}
style={{ height: '100vh', width: '100%' }}
maxBounds={[
[58.619777025081675, -10.437011718750002],
[49.66762782262194, 3.3618164062500004],
]}
>
<LayerGroup>
<D3Layer></D3Layer>
</LayerGroup>
<MyMapEvents />
<TileLayer
attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
/>

<NavBar mapZoom={mapSettings.zoom} activeNav={activeNav} navClick={navClick} show={show} />
<Overlay show={show} />
</MapContainer>
</>
);
};
export default MapComponent;

然后我想把D3代码放入D3Layer组件。

目前组件返回带有hello的h1标签,但这隐藏在地图后面。如果有人能得到一些基本的工作,即使只是得到我的基本设置,以显示基本的东西,如一个正方形,我敢肯定,我可以计算json

的导入

感谢

这是一个使用d3库在reactreact-leaflet中改编的导入正方形的示例,通过创建自定义组件,并将示例代码包含在useEffect中。

安装d3库和d3-geo库。

在这个例子中,我直接从文件中导入json但你也可以使用d3.json

获取它
import L from "leaflet";
import * as d3 from "d3";
import * as d3Geo from "d3-geo";
import geoShape from "./rectangle.json";

function D3Layer() {
const map = useMap();
useEffect(() => {
const svg = d3.select(map.getPanes().overlayPane).append("svg");
const g = svg.append("g").attr("class", "leaflet-zoom-hide");

//  create a d3.geo.path to convert GeoJSON to SVG
const transform = d3Geo.geoTransform({
point: projectPoint
}),
path = d3Geo.geoPath().projection(transform);

// create path elements for each of the features
const d3_features = g
.selectAll("path")
.data(geoShape.features)
.enter()
.append("path");

map.on("viewreset", reset);

reset();

// fit the SVG element to leaflet's map layer
function reset() {
const bounds = path.bounds(geoShape);

const topLeft = bounds[0],
bottomRight = bounds[1];

svg
.attr("width", bottomRight[0] - topLeft[0])
.attr("height", bottomRight[1] - topLeft[1])
.style("left", topLeft[0] + "px")
.style("top", topLeft[1] + "px");

g.attr(
"transform",
"translate(" + -topLeft[0] + "," + -topLeft[1] + ")"
);

// initialize the path data
d3_features
.attr("d", path)
.style("fill-opacity", 0.7)
.attr("fill", "blue");
}

// Use Leaflet to implement a D3 geometric transformation.
function projectPoint(x, y) {
var point = map.latLngToLayerPoint(new L.LatLng(y, x));
this.stream.point(point.x, point.y);
}
}, []);
return null;
}

演示

最新更新