Published
Edited
Sep 1, 2020
Importers
Insert cell
Insert cell
function shpToGeoJSON(zip) {
return new Promise(resolve => {
const worker = new Worker(workerScript);

function messaged({ data }) {
resolve(data);
}

invalidation.then(() => worker.terminate());
worker.addEventListener('message', messaged);
worker.postMessage(zip);
});
}
Insert cell
workerScript = {
const blob = new Blob(
[
`
importScripts("${await require.resolve("jszip@3/dist/jszip.min.js")}");
importScripts("${await require.resolve("shapefile@0.6")}");

onmessage = async (event) => {
// prepare to peek into archive
const archive = await JSZip.loadAsync(event.data);

// find all .shp files in the archive
const files = archive.file(/\.shp$/);

const results = Object.create(null);

for (const file of files) {
// the ID of this file will be the file name minus the ".shp"
const name = file.name.replace('.shp', '');

// read out the .shp file to a Buffer
const shp = await file.async('arraybuffer');

// build the file path to the possible .dbf file, and seek it
const dbfFile = archive.file(\`\${name}.dbf\`);

// if we succeeded in finding the dbfFile, read it as a Buffer as well, otherwise continue
const dbf = dbfFile ? await dbfFile.async('arraybuffer') : undefined;

// convert the .shp file to GeoJSON
const geojson = await shapefile.read(shp, dbf);

// ensure that the winding order is correct
results[name] = geojson;
}

postMessage(results);
close();
};
`
],
{ type: "text/javascript" }
);
const script = URL.createObjectURL(blob);
invalidation.then(() => URL.revokeObjectURL(script));
return script;
}
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more