Skip to content

Instantly share code, notes, and snippets.

@albjeremias
Created May 27, 2026 22:55
Show Gist options
  • Select an option

  • Save albjeremias/0d591bbd703ac2b9bd835b40118cd14f to your computer and use it in GitHub Desktop.

Select an option

Save albjeremias/0d591bbd703ac2b9bd835b40118cd14f to your computer and use it in GitHub Desktop.
import kml to geojson with lines and umap colors
const tj = require("@tmcw/togeojson");
const fs = require("fs");
const DOMParser = require("xmldom").DOMParser;
const turf = require("@turf/polygon-to-line");
const filename = process?.argv[2];
let keepPolygons = process?.argv[3];
if (!filename) {
console.error('Usage: node convertgeojson.js <file>, file should be in geojson');
process.exit(1);
}
if(!keepPolygons || keepPolygons != '-k'){
keepPolygons = false;
}else{
console.log('keeping polygons....')
keepPolygons = true;
}
const kml = new DOMParser().parseFromString(fs.readFileSync(filename, "utf8"));
let converted = tj.kml(kml);
const convertGeometryCollections = (converted) => {
let geoCollectionFeatures = converted.features.filter((_feat) => {
if (_feat.geometry.type == 'GeometryCollection') {
return true;
}
return false;
})
let nonGeoCollectionFeatures = converted.features.filter((_feat) => {
if (_feat.geometry.type != 'GeometryCollection') {
return true;
}
return false;
})
let all = []
geoCollectionFeatures.map((_feat) => {
let j = 0;
_feat.geometry.geometries.map((geome) => {
j++;
all.push({ ..._feat, geometry: geome, properties: { ..._feat.properties, name: `${_feat.properties.name}-${j}` } })
})
})
converted.features = [...nonGeoCollectionFeatures, ...all]
return converted
}
const convertColorsUmap = (converted) => {
converted.features = converted.features.map((feature) => {
let extraProperties = {}
if (feature.properties.fill) {
extraProperties = { "color": feature.properties.fill }
}
return { ...feature, properties: { ...feature.properties, "_umap_options": extraProperties } }
})
return converted
}
const convertPolygonsToPaths = (converted) => {
converted.features = converted.features.map((feature) => {
let _geometry = { ...feature.geometry }
if (feature.geometry.type == 'Polygon') {
const _feature = turf.polygonToLine(feature.geometry)
_geometry = _feature.geometry
}
return { ...feature, geometry: { ..._geometry }}
})
return converted
}
if(!keepPolygons){
converted = convertGeometryCollections(converted);
converted = convertPolygonsToPaths(converted);
}
converted = convertColorsUmap(converted);
fs.writeFileSync(`./converted.geojson`, JSON.stringify(converted, null, 2));
{
"dependencies": {
"@tmcw/togeojson": "^7.1.2",
"@turf/polygon-to-line": "^7.3.5",
"xmldom": "^0.6.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment