Skip to content

Instantly share code, notes, and snippets.

@Gyvastis
Forked from tyohan/removeduplicatevertice.js
Created March 9, 2023 09:47
Show Gist options
  • Save Gyvastis/89686f249e6b722477d8c26e9eb8dd2e to your computer and use it in GitHub Desktop.
Save Gyvastis/89686f249e6b722477d8c26e9eb8dd2e 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));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment