Created
October 6, 2014 13:42
-
-
Save digitalsadhu/fa9667f3533f07e0fa4e to your computer and use it in GitHub Desktop.
Intersects geojson features with a POSTGIS database
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 | |
'use strict'; | |
var through = require('through2') | |
, geojsonStream = require('geojson-stream') | |
, fs = require('fs') | |
, chalk = require('chalk') | |
, pg = require('pg') | |
var client = new pg.Client({ | |
user: 'digitalsadhu', | |
database: 'tmps' | |
}) | |
var queries = { | |
intersection: 'SELECT count(*) FROM tmps WHERE ST_Intersects(geom, ' + | |
'ST_GeomFromGeoJSON($1)) AND type = $2' | |
} | |
var weightings = { | |
'notsignificant': 4, | |
'major': 7, | |
'closure': 10 | |
} | |
function intersection(type, geojson, client, cb) { | |
client.query({ | |
text: queries.intersection, | |
values: [geojson.geometry, type] | |
}, cb) | |
} | |
function calculateIntersection(type) { | |
return through.obj(function (chunk, enc, cb) { | |
intersection(type, chunk, client, function (err, result) { | |
if (result.rows[0].count > 0) { | |
chunk.properties.weighting = weightings[type] | |
} | |
this.push(chunk) | |
cb() | |
}.bind(this)) | |
}) | |
} | |
function removeNonIntersectingChunks() { | |
return through.obj(function (chunk, enc, cb) { | |
if (chunk.properties.weighting) this.push(chunk) | |
cb() | |
}) | |
} | |
client.connect(function(err) { | |
if(err) return console.error('could not connect to postgres', err) | |
fs.createReadStream(process.argv[2]) | |
.pipe(geojsonStream.parse()) | |
.pipe(calculateIntersection('notsignificant')) | |
.pipe(calculateIntersection('major')) | |
.pipe(calculateIntersection('closure')) | |
.pipe(removeNonIntersectingChunks()) | |
.pipe(geojsonStream.stringify()) | |
.on('end', function () { | |
process.exit(0) | |
}) | |
.pipe(process.stdout) | |
.on('error', function (err) { | |
console.error(chalk.red(err.message)) | |
console.trace() | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment