Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convert GPX/KML to geojson #61

Merged
merged 26 commits into from
May 4, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
e483044
convert KML and GPX to GeoJSON
wilhelmberg Mar 10, 2016
a8d1df1
GPX: drop 'track_points' and 'route_points'
wilhelmberg Mar 16, 2016
5ab4de5
add metadata and index file to new bundle dirs, still troubleshooting…
Mar 16, 2016
5e1d36b
split out kml togeojson tests and moved indexing
Mar 18, 2016
677a427
flush and close datasets before mapnik-indexing them
wilhelmberg Mar 20, 2016
4f96667
togeojson: release objects to be able to index
wilhelmberg Mar 20, 2016
43d2630
[wip] make tests work again
wilhelmberg Mar 20, 2016
1952055
split out tests
Mar 21, 2016
8dc4291
manually release gdal's reference to dataset
wilhelmberg Mar 22, 2016
abf63bc
fix mbtiles test
wilhelmberg Mar 22, 2016
44fc555
fix GPX test
wilhelmberg Mar 22, 2016
c9ca030
fix kml test
wilhelmberg Mar 22, 2016
fa90501
add 10MB filter for indexing kml/gpx layers
Mar 23, 2016
a08b2ca
unlink 2 tmp files of test/spatial-index.test.js
wilhelmberg Mar 24, 2016
d07f007
travis?
Mar 24, 2016
f781e3c
bump mapnik-omnivore to include newest node-mapnik
Mar 24, 2016
cd5474e
node-mapnik doesnt support builds for node v0.12
Mar 24, 2016
a61209a
re-add special character layer test, it got left behind
Mar 24, 2016
d6af91f
travis? delete temp dirs of `spatial-index.test.js`
wilhelmberg Mar 25, 2016
fc21183
WIP not yet finished, clean up temporary test data
wilhelmberg Mar 25, 2016
2a20b12
oops, style errors
wilhelmberg Mar 25, 2016
338d5a2
clean up temp data after 'npm test'
wilhelmberg Mar 28, 2016
5aad818
what is data?
Apr 11, 2016
4cc9d80
`Merge branch 'master' into togeojson
Apr 26, 2016
197766e
remove unneeded log
May 4, 2016
18c3a26
udpate mapnik-om
May 4, 2016
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"rules": {
"indent": [2, 2],
"quotes": [2, "single"],
"no-console": [0],
"semi": [2, "always"]
},
"env": {
"node": true
},
"globals": {
"process": true,
"module": true,
"require": true
},
"extends": "eslint:recommended"
}
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
node_modules
preprocessors/test*
test/fixtures/*.aux.xml
10 changes: 7 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"description": "",
"main": "index.js",
"scripts": {
"pretest": "jshint index.js bin parts preprocessors test && jscs index.js bin parts preprocessors test",
"pretest": "jshint index.js bin parts preprocessors test && eslint index.js bin parts preprocessors test && jscs index.js bin parts preprocessors test",
"test": "tape test/*.test.js",
"coverage": "istanbul cover tape test/*.test.js && coveralls < ./coverage/lcov.info"
},
Expand All @@ -23,18 +23,21 @@
"homepage": "https://github.com/mapbox/preprocessorcerer",
"devDependencies": {
"concat-stream": "^1.4.8",
"eslint": "^1.6.0",
"jscs": "^1.10.0",
"jshint": "^2.6.0",
"tape": "^3.4.0",
"tilelive": "^5.7.0",
"istanbul": "~0.3.17",
"coveralls": "~2.11.2",
"checksum": "^0.1.1"
"checksum": "^0.1.1",
"rimraf": "^2.5.2"
},
"dependencies": {
"bytetiff": "~0.3.0",
"gdal": "~0.8.0",
"mapbox-file-sniff": "~0.4.0",
"mapnik-omnivore": "~7.4.0",
"mapnik": "~3.5.0",
"mkdirp": "^0.5.0",
"mbtiles": "^0.8.0",
Expand All @@ -55,6 +58,7 @@
"preset": "airbnb",
"requireCamelCaseOrUpperCaseIdentifiers": null,
"disallowMultipleVarDecl": true,
"requireMultipleVarDecl": null
"requireMultipleVarDecl": null,
"validateLineBreaks": null
}
}
12 changes: 8 additions & 4 deletions parts/mbtiles-byTiles.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,15 @@ module.exports = function splitBySize(filepath, info, callback) {
}
else if (err) return callback(err);

var maxTilesPerJob = 100000;
var result = tilesResult.count + gridsResult.count;
if (!result) return callback(new Error('no tiles or grids'));
src.close(function(err) {
if (err) return callback(err);
src = null;
var maxTilesPerJob = 100000;
var result = tilesResult.count + gridsResult.count;
if (!result) return callback(new Error('no tiles or grids'));

callback(null, Math.min(50, Math.ceil(result / maxTilesPerJob)));
callback(null, Math.min(50, Math.ceil(result / maxTilesPerJob)));
});
});
});
});
Expand Down
5 changes: 4 additions & 1 deletion preprocessors/geojson-bom.preprocessor.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@ module.exports.criteria = function(infile, info, callback) {
fs.read(fd, buf, 0, 3, 0, function(err) {
if (err) return callback(err);
var strip = buf[0] === 0xef && buf[1] === 0xbb && buf[2] == 0xbf;
callback(null, strip);
fs.close(fd, function(err) {
if (err) return callback(err);
callback(null, strip);
});
});
});
};
4 changes: 3 additions & 1 deletion preprocessors/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ var preprocessors = [
'tif-reproject.preprocessor',
'shp-index.preprocessor',
'geojson-bom.preprocessor',
'spatial-index.preprocessor'
'spatial-index.preprocessor',
'togeojson-kml.preprocessor',
'togeojson-gpx.preprocessor'
];

// Loads each *.preprocessor.js file and builds an array of them
Expand Down
2 changes: 1 addition & 1 deletion preprocessors/shp-index.preprocessor.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ var path = require('path');
var fs = require('fs');
var spawn = require('child_process').spawn;
var mapnik = require('mapnik');
var shapeindex = path.resolve(mapnik.module_path, 'shapeindex');
var shapeindex = path.resolve(mapnik.module_path, 'shapeindex' + (process.platform === 'win32' ? '.exe' : ''));
if (!fs.existsSync(shapeindex)) {
throw new Error('shapeindex does not exist at ' + shapeindex);
}
Expand Down
3 changes: 3 additions & 0 deletions preprocessors/tif-reproject.preprocessor.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ module.exports.criteria = function(filepath, info, callback) {
}
catch (err) { return callback(err); }

ds.close();
ds = null;

if (projection === sm) callback(null, false);
else callback(null, true);
};
8 changes: 6 additions & 2 deletions preprocessors/tif-toBytes.preprocessor.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ module.exports.criteria = function(filepath, info, callback) {
try { band = ds.bands.get(1); }
catch (err) { return callback(err); }

if (band.dataType === gdal.GDT_UInt16) return callback(null, true);
callback(null, false);
var is16 = band.dataType === gdal.GDT_UInt16;

ds.close();
ds = null;

callback(null, is16);
};
156 changes: 156 additions & 0 deletions preprocessors/togeojson-gpx.preprocessor.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
var gdal = require('gdal');
var fs = require('fs');
var mkdirp = require('mkdirp');
var queue = require('queue-async');
var spawn = require('child_process').spawn;
var path = require('path');
var digest = require('mapnik-omnivore').digest;
var mapnik = require('mapnik');
var mapnik_index = path.resolve(mapnik.module_path, 'mapnik-index' + (process.platform === 'win32' ? '.exe' : ''));
if (!fs.existsSync(mapnik_index)) {
throw new Error('mapnik-index does not exist at ' + mapnik_index);
}

//disable in production
//gdal.verbose();

module.exports = function(infile, outdirectory, callback) {
mkdirp(outdirectory, function(err) {
if (err) return callback(err);

var geojson_files = [];
var ds_gpx;
var full_feature_cnt = 0;
var wgs84 = gdal.SpatialReference.fromEPSG(4326);

try {
ds_gpx = gdal.open(infile);
}
catch (err) {
return callback(new Error(err));
}

ds_gpx.layers.forEach(function(lyr_gpx) {
//drop point layers as they can get really huge
if (lyr_gpx.name === 'track_points' || lyr_gpx.name === 'route_points') {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this represent a breaking change from present behavior? That is, would these layers be included in a GPX upload today?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

return;
}

var feat_cnt = lyr_gpx.features.count(true);
if (feat_cnt === 0) {
return;
}

var geojson;
var lyr_name;
var out_ds;
var out_name;

try {
lyr_name = lyr_gpx.name;
out_name = path.join(outdirectory, lyr_name + '.geojson');
out_ds = gdal.open(out_name, 'w', 'GeoJSON');
geojson = out_ds.layers.create(lyr_name, wgs84, lyr_gpx.geomType);
}
catch (err) {
return callback(new Error(err));
}

lyr_gpx.features.forEach(function(gpx_feat) {
//skip null or empty geometries
var geom = gpx_feat.getGeometry();
if (!geom) {
return;
} else {
if (geom.isEmpty()) {
return;
}

if (!geom.isValid()) {
return;
}
}

geojson.features.add(gpx_feat);
full_feature_cnt++;
});

geojson.flush();
out_ds.flush();
out_ds.close();

//release objects to be able to index
geojson = null;
out_ds = null;

geojson_files.push(out_name);
});

ds_gpx.close();
if (full_feature_cnt === 0) {
return callback(new Error('GPX does not contain any valid features.'));
}

// Create metadata file for original gpx source
var metadatafile = path.join(outdirectory, '/metadata.json');
digest(infile, function(err, metadata) {
if (err) return callback(err);
fs.writeFile(metadatafile, JSON.stringify(metadata), function(err) {
if (err) return callback(err);
return createIndices(callback);
});
});

function createIndices(callback) {
// create mapnik index for each geojson layer
var q = queue();
geojson_files.forEach(function(gj) {
q.defer(createIndex, gj);
});

q.awaitAll(function(err) {
if (err) return callback(err);
return callback();
});
}

function createIndex(layerfile, callback) {
// Finally, create an .index file in the output dir (if layer is greater than index_worthy_size).
// mapnik-index will automatically add ".index" to the end of the original filename
fs.stat(layerfile, function(err, stats) {
if (err) return callback(err);

// check size is warrants creating an index
if (stats.size >= module.exports.index_worthy_size) {
var data = '';
var p = spawn(mapnik_index, [layerfile, '--validate-features'])
.once('error', callback)
.on('exit', function() {
// If error printed to --validate-features log
if (data.indexOf('Error') != -1) {
return callback(data);
}
else return callback();
});

p.stderr.on('data', function(d) {
d.toString();
data += d;
});
} else {
return callback();
}
});
}
});
};

module.exports.description = 'Convert GPX to GeoJSON';
module.exports.index_worthy_size = 10 * 1024 * 1024; // 10 MB

module.exports.criteria = function(filepath, info, callback) {

if (info.filetype !== 'gpx') return callback(null, false);

callback(null, true);
};
Loading