Showing GeoJSON, KML, GPX and WKT
Convert common GIS formats and show them on the map, including files users open
useSphereUtils converts KML, GPX, WKT, GML, Esri JSON and TopoJSON to GeoJSON, and <GeoJson> draws it:
Click a shape to see its name.
Open a file
import { GeoJson, SphereMap, useSphereUtils, type GeoJSON } from "gistda-sphere-react";
import { useState } from "react";
function FileViewer() {
const { kmlToGeoJSON, gpxToGeoJSON, wktToGeoJSON } = useSphereUtils();
const [data, setData] = useState<GeoJSON | null>(null);
const [error, setError] = useState<string | null>(null);
async function open(file: File) {
const text = await file.text();
const extension = file.name.split(".").pop()?.toLowerCase();
try {
if (extension === "kml") setData(await kmlToGeoJSON(text));
else if (extension === "gpx") setData(await gpxToGeoJSON(text));
else if (extension === "wkt") setData(await wktToGeoJSON(text));
else setData(JSON.parse(text));
setError(null);
} catch (reason) {
setError(String(reason));
}
}
return (
<>
<input
type="file"
accept=".geojson,.json,.kml,.gpx,.wkt"
onChange={(event) => event.target.files?.[0] && open(event.target.files[0])}
/>
{error && <p role="alert">{error}</p>}
<SphereMap style={{ height: 500 }}>
{data && (
<GeoJson
data={data}
fitBounds={{ padding: 40, maxZoom: 16 }}
style={{ lineColor: "#059669", fillColor: "rgba(16,185,129,.25)", lineWidth: 3 }}
/>
)}
</SphereMap>
</>
);
}Shapefiles
Shapefiles need a separate library. GISTDA's examples use shpjs, which reads a zipped Shapefile into GeoJSON:
import shp from "shpjs"; // npm install shpjs
async function openShapefile(file: File) {
const result = await shp(await file.arrayBuffer());
// A zip with several layers gives an array of feature collections.
setData(Array.isArray(result) ? result[0] : result);
}Export drawn shapes
Every shape ref has toGeoJSON(), so you can save what users draw:
import type { PolygonRef } from "gistda-sphere-react";
import { useRef } from "react";
// Filled by ref callbacks: <Polygon ref={(ref) => { shapes.current[index] = ref; }} />
const shapes = useRef<(PolygonRef | null)[]>([]);
const features = shapes.current.map((shape) => shape?.toGeoJSON()).filter(Boolean);
const file = new Blob([JSON.stringify({ type: "FeatureCollection", features })], {
type: "application/geo+json",
});The playground's Draw tab imports all four formats and exports drawings as GeoJSON.
Other coordinate systems
Data in a projected coordinate system, such as UTM zone 47N, can be converted with project:
import { useSphereUtils } from "gistda-sphere-react";
const { project } = useSphereUtils();
const [lon, lat] = (await project(
"+proj=longlat +datum=WGS84",
[662_190, 1_521_385],
"+proj=utm +zone=47 +datum=WGS84 +units=m"
)) as number[];