Skip to content

Instantly share code, notes, and snippets.

@vinayakkulkarni
Created September 14, 2021 09:48
Show Gist options
  • Save vinayakkulkarni/717f55215716763d47f8aed189449552 to your computer and use it in GitHub Desktop.
Save vinayakkulkarni/717f55215716763d47f8aed189449552 to your computer and use it in GitHub Desktop.
CSV to GeoJSON Parser in Web Worker
import { csvParse } from 'd3-dsv';
import { Feature, FeatureCollection, Point } from 'geojson';
function snooze(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
addEventListener('message', async (event: MessageEvent) => {
const { payload, sleep } = event.data.message;
await snooze(sleep);
const data = csvParse(payload);
const geojson = await transformGeoJSON(data);
postMessage(geojson);
});
async function transformGeoJSON(payload: any): Promise<FeatureCollection> {
const geojson: FeatureCollection<Point> = {
type: 'FeatureCollection',
features: [],
} as FeatureCollection<Point>;
for await (const t of payload) {
geojson.features.push({
type: 'Feature',
properties: {
userId: t?.userId || null,
userName: t?.userName || null,
},
geometry: {
type: 'Point',
coordinates: [
parseFloat(t?.longitude) || 0,
parseFloat(t?.latitude) || 0,
],
},
} as Feature<Point>);
}
return geojson;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment