Skip to content

Instantly share code, notes, and snippets.

@tyohan
Last active April 16, 2023 23:01
Show Gist options
  • Save tyohan/dae708420b8bb46d1f8e to your computer and use it in GitHub Desktop.
Save tyohan/dae708420b8bb46d1f8e to your computer and use it in GitHub Desktop.
Remove duplicate vertice on mongodb geojson collection
#!/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));
@tyohan
Copy link
Author

tyohan commented Sep 26, 2015

How to use it
node geojsontomongo.js <geojson-file>

Example
node geojsontomongo.js districts.geojson

@moazam1
Copy link

moazam1 commented Aug 28, 2018

@tyohan your script didn't work for me. It's only keeping one coordinate in geojson

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment