Last active
March 24, 2016 19:18
-
-
Save isc-rsingh/56153cc18c056058f6e7 to your computer and use it in GitHub Desktop.
Converts an on-disk Shapefile into GeoJSON and imports the data into a CouchDB-compatible database (e.g. Cloudant) using node.js.
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
/** | |
* Converts an on-disk Shapefile into GeoJSON and imports the data into a CouchDB-compatible database, | |
* like Cloudant.com! | |
* requires Node.js and the 'cradle' and 'shapefile' modules. | |
* - installation: save this code to a file called index.js | |
* - at the shell: npm install cradle | |
* - at the shell: npm install shapefile | |
* - at the shell, run the program: node index.js | |
*/ | |
var cradle = require('cradle'); // npm install cradle | |
var shapefile = require('shapefile'); // npm install shapefile | |
//-- variables you must set | |
var hostname = 'http://localhost'; | |
var dbport = 5984; // change to 443 for https hostnames | |
var dbname = 'testshp'; // ex: testshapefile (TODO: or null to use shapefile name) | |
var username = 'rajsingh'; | |
var pw = process.env.couchdb_password; // at the shell type: export couchdb_password="yourpwhere" | |
var shpfile = "myshp.shp"; | |
//-- end variables you must set | |
// connect to your account | |
var conn = new(cradle.Connection)(hostname, dbport, { | |
auth: { username: username, password: pw }, | |
cache: true, raw: false, forceSave: true | |
}); | |
// check for database existence | |
var db = conn.database(dbname); | |
db.exists(function(err, exists){ | |
if (err) { | |
console.error('ERROR: %s', err); | |
} else if (exists) { | |
console.log('Database %s exists, adding data to it...', dbname); | |
importShapefile(); | |
} else { | |
console.log('Creating database %s', dbname); | |
db.create(); | |
importShapefile(); | |
} | |
}); | |
function importShapefile() { | |
reader = shapefile.reader(shpfile); | |
reader.readHeader(function(err, header){ | |
if (err) throw error; | |
console.log('header', header); | |
readNextRecord(); | |
}); | |
} | |
function readNextRecord() { | |
reader.readRecord(function(error, record) { | |
if (error) throw error; | |
if ( record == shapefile.end ) return reader.close(); | |
db.save(record, function(err, response) { | |
if (err) console.error(err); | |
else console.log(response); | |
}); | |
setImmediate(readNextRecord); | |
}); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment