Last active
April 16, 2023 23:01
-
-
Save tyohan/dae708420b8bb46d1f8e to your computer and use it in GitHub Desktop.
Remove duplicate vertice on mongodb geojson collection
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
#!/usr/bin/env node | |
var path=require('path'); | |
var fs = require('fs'); | |
if(process.argv.length<3) | |
throw new Error('You\'re not passing the geojson file'); | |
var file=process.argv[2]; | |
var gjFile=fs.statSync(file); | |
if(!gjFile.isFile()) | |
throw new Error('File not found'); | |
var gjString=fs.readFileSync(file,'utf8'); | |
var gJson=JSON.parse(gjString); | |
var removeDuplicate=function(point,coordinates,index){ | |
var duplicate=false; | |
var duplicateIndex=null; | |
var lastIndex=coordinates.length-1; | |
coordinates.forEach(function(el,j){ | |
if(point[0]===el[0] && point[1]===el[1] && index!==j && j<lastIndex && j!==0){ | |
duplicate= true; | |
duplicateIndex=j; | |
console.log('found duplicate on '+duplicateIndex); | |
console.log(point[0]+'='+el[0]+' && '+ point[1]+'='+el[1]); | |
} | |
}); | |
if(duplicate===true){ | |
console.log('remove duplicate on '+duplicateIndex); | |
coordinates.splice(duplicateIndex, 1); | |
} | |
//else | |
//print('No duplicate'); | |
return coordinates; | |
}; | |
gJson.features.forEach(function(feature,y){ | |
if(feature.geometry.type==='Polygon'){ | |
feature.geometry.coordinates[0].forEach(function(coordinates,i){ | |
coordinates.forEach(function(point,index){ | |
var coordinate=removeDuplicate(point,coordinates,index); | |
feature.geometry.coordinates[0]=coordinate; | |
}); | |
}); | |
}else if(feature.geometry.type==='MultiPolygon'){ | |
feature.geometry.coordinates.forEach(function(points,j){ | |
points.forEach(function(coordinates,i){ | |
coordinates.forEach(function(point,index){ | |
var coordinate=removeDuplicate(point,coordinates,index); | |
feature.geometry.coordinates[j][i]=coordinate; | |
}); | |
}); | |
}); | |
} | |
//update object | |
gJson.features[y]=feature; | |
}); | |
fs.writeFileSync(path.dirname(file)+'/clean-'+path.basename(file), JSON.stringify( gJson)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to use it
node geojsontomongo.js <geojson-file>
Example
node geojsontomongo.js districts.geojson