Skip to content

Instantly share code, notes, and snippets.

@reyemtm
Last active March 12, 2020 13:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reyemtm/66e1190567a015de11efb8984b0a9fb7 to your computer and use it in GitHub Desktop.
Save reyemtm/66e1190567a015de11efb8984b0a9fb7 to your computer and use it in GitHub Desktop.
mergeNamedShapefilesToGeoJSON
//MAP THROUGH ALL FILES TO GET AN ARRAY OF SHAPEFILES TO CONVERT
//MAP THROUGH EACH FILE TO GET FEATURES AND PUSH TO MASTER, ADD FILENAME AS TYPE AND COLLECT FIELDS
//MAP THROUGH MASTER AND ADD MISSING FIELDS
var fs = require("fs");
var shapefile = require("shapefile");
var converted = {
type: "FeatureCollection",
features: []
}
var allFiles = fs.readdirSync("../Street Signs");
var shapeFiles = allFiles.filter(f => {
return f.split(".")[1] === "shp"
})
console.log("total shapefiles to convert", shapeFiles.length)
//TESTING
// var test = [];
// test.push(shapeFiles[0])
// test.push(shapeFiles[1])
// console.log(test)
// test.map(file => {
// convert(file)
// })
shapeFiles.map((file,i) => {
var index = i + 1
convert(file, index, shapeFiles.length)
})
var convertedCount = 0;
function convert(file,index,length) {
var signType = file.split(".")[0];
var propertiesArray = [];
shapefile.open(file)
.then(source => source.read()
.then(function toGeoJSON(result) {
if (result.done) {
convertedCount = convertedCount + 1;
console.log("converting", file, convertedCount, "of", length);
var newProps = getProps(converted);
newProps.map(p => {
if (propertiesArray.indexOf(p) < 0) propertiesArray.push(p)
})
converted.features.map(f => {
propertiesArray.map(p => {
if (!f.properties[p]) {
f.properties[p] = null
}
})
});
if (convertedCount === length) {
//APPLY ANY FINAL CONVERSIONS ON THE ENTIRE DATASET
// converted.features.map(f => {
// DO SOMETHING
// })
fs.writeFileSync("_convertedGeoJSON.json", JSON.stringify(converted, 0, 2))
console.log("done!!")
}
return
};
result.value.properties.signtype = signType;
converted.features.push(result.value)
// console.log(converted.features)
return source.read().then(toGeoJSON);
}))
.catch(error => console.error(error.stack));
}
function getProps(geojson) {
var props = [];
geojson.features.map(f => {
for (var p in f.properties) {
props.push(p)
}
})
return props
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment