Skip to content

Instantly share code, notes, and snippets.

@digitalsadhu
Created October 6, 2014 13:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save digitalsadhu/3fb61a02a02d7f35d6fe to your computer and use it in GitHub Desktop.
Save digitalsadhu/3fb61a02a02d7f35d6fe to your computer and use it in GitHub Desktop.
Script to convert osm geojson data to osm ways geojson feature pairs
#!/usr/bin/env node
'use strict';
//Streaming parser that filters out osm data leaving just ways.
//Ways are then broken down into node pairs.
//
//ie.
//{
// "type":"Feature",
// "id":"way/292294676/3", <-- id gets incremented
// "properties":{
// "cycleway":"lane",
// "highway":"primary",
// "lanes":"2",
// "maxspeed":"50",
// "name":"Harewood Road",
// "oneway":"yes",
// "source":"Bing",
// "id":"way/292294676"
// },
// "geometry":{
// "type":"LineString", <-- linestring broken into just 2 nodes
// "coordinates":[
// [172.58113310000002,-43.4852091],
// [172.57978799999998,-43.48464799999999]
// ]
// }
//}
var JSONStream = require('JSONStream')
, through = require('through2')
, geojsonStream = require('geojson-stream')
, fs = require('fs')
, chalk = require('chalk')
fs.createReadStream(process.argv[2])
//parse out each feature block
.pipe(JSONStream.parse('features.*'))
//throw out anything but ways
.pipe(through.obj(function (chunk, enc, cb) {
if (chunk.id.match(/way\/.*/)) this.push(chunk)
cb()
}))
//split each way linestring into linestrings with just 2 node pairs
.pipe(through.obj(function (chunk, enc, cb) {
var feature = chunk
, id = feature.id
, coordinates = feature.geometry.coordinates
, i = 0
while(coordinates.length > 1) {
//append to id for uniqueness. eg. way/292294608 becomes way/292294608/0
feature.id = feature.properties.id = id + '/' + i++
//shift the first node off the array and set as the new linestring
//together with the node now at the front of the array
feature.geometry.coordinates = [coordinates.shift(), coordinates[0]]
this.push(feature)
}
cb()
}))
//stream into a geojson feature collection
.pipe(geojsonStream.stringify())
//stream into the std out
.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