Created
September 14, 2021 09:48
-
-
Save vinayakkulkarni/717f55215716763d47f8aed189449552 to your computer and use it in GitHub Desktop.
CSV to GeoJSON Parser in Web Worker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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