forked from MapComplete/MapComplete
		
	
		
			
				
	
	
		
			58 lines
		
	
	
	
		
			1.9 KiB
		
	
	
	
		
			TypeScript
		
	
	
	
	
	
			
		
		
	
	
			58 lines
		
	
	
	
		
			1.9 KiB
		
	
	
	
		
			TypeScript
		
	
	
	
	
	
import { readFileSync, writeFileSync } from "fs"
 | 
						|
import Script from "../Script"
 | 
						|
import { parse } from "papaparse"
 | 
						|
import { FeatureCollection, Point } from "geojson"
 | 
						|
 | 
						|
class ZHVcsv2GeoJson extends Script {
 | 
						|
    constructor() {
 | 
						|
        super("Converts a CSV file with ZHV data to GeoJSON format. Usage: csv-file output-file")
 | 
						|
    }
 | 
						|
 | 
						|
    async main(args: string[]): Promise<void> {
 | 
						|
        const csvFile = args[0]
 | 
						|
        const outputFile = args[1]
 | 
						|
 | 
						|
        if (!csvFile || !outputFile) {
 | 
						|
            console.error("Usage: csv-file output-file")
 | 
						|
            return
 | 
						|
        }
 | 
						|
 | 
						|
        // Read the CSV file and parse it using PapaParse
 | 
						|
        const text = readFileSync(csvFile, "utf-8")
 | 
						|
        const parsed = parse(text, {
 | 
						|
            header: true,
 | 
						|
            dynamicTyping: false,
 | 
						|
        })
 | 
						|
 | 
						|
        console.log(`Parsed ${parsed.data.length} rows from ${csvFile}`)
 | 
						|
        console.log(`First row:`, parsed.data[0])
 | 
						|
 | 
						|
        // Drop all rows that do not have a valid latitude and longitude
 | 
						|
        parsed.data = parsed.data.filter((row: any) => {
 | 
						|
            return row["Latitude"] && row["Longitude"]
 | 
						|
        })
 | 
						|
 | 
						|
        // Convert the parsed data to GeoJSON format
 | 
						|
        const geoJson: FeatureCollection<Point> = {
 | 
						|
            type: "FeatureCollection",
 | 
						|
            features: parsed.data.map((row: any) => ({
 | 
						|
                type: "Feature",
 | 
						|
                geometry: {
 | 
						|
                    type: "Point",
 | 
						|
                    coordinates: [
 | 
						|
                        parseFloat(row["Longitude"].replace(",", ".")),
 | 
						|
                        parseFloat(row["Latitude"].replace(",", ".")),
 | 
						|
                    ],
 | 
						|
                },
 | 
						|
                properties: row,
 | 
						|
            })),
 | 
						|
        }
 | 
						|
 | 
						|
        console.log(`First feature:`, geoJson.features[0])
 | 
						|
 | 
						|
        // Write the GeoJSON output to the specified file
 | 
						|
        writeFileSync(outputFile, JSON.stringify(geoJson), "utf-8")
 | 
						|
    }
 | 
						|
}
 | 
						|
 | 
						|
new ZHVcsv2GeoJson().run()
 |