I have been using a GeoJson file for the react-leaflet map, but the file was too big and I got sent a TopoJson file. There is not much information on how to use this with react-leaflet.
This is my code -
import { Map, TileLayer, GeoJSON } from "react-leaflet";
const topoJson = require("./assets/topo.json");
<Map center={[36.778259, -119.417931]} zoom={4}>
<TileLayer
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
/>
<GeoJSON data={topoJson} />
</Map>
This is the error when it renders - Error: Invalid GeoJSON object.
Any ideas or feedback on how to use a topoJson file whiles using the react-leaflet library, thanks!
GeoJSON
component from react-leflet
does not support rendering TopoJSON, the following component could be introduced (which extends GeoJSON
component and utilizes topojson
) for that matter:
import React, { useRef, useEffect } from "react";
import { GeoJSON, withLeaflet } from "react-leaflet";
import * as topojson from "topojson";
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);
Result
Update There is a dependency to topojson
package but since nowadays it is deprecated, topojson-client
is utilized instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.