Skip to content

Instantly share code, notes, and snippets.

@wboykinm
Last active December 7, 2019 21:40
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wboykinm/0d87f55caa301924e924d7c02d330e25 to your computer and use it in GitHub Desktop.
Save wboykinm/0d87f55caa301924e924d7c02d330e25 to your computer and use it in GitHub Desktop.
Using vector-tile-js to get water polygons as geojson tiles

Using vector-tile-js to get water polygons as geojson tiles

Usage

npm install
node get-geojson.js <tile address>

<tile address> is a set of tile coordinates passed in as a string in the form [x,y,z] e.g. node get-geojson.js "[958, 1696, 12]"

// SPIT OUT A NAMED GEOJSON FILE FOR EACH INPUT TILE ADDRESS
var fs = require('fs');
var request = require('request');
var turf = require('turf');
var Protobuf = require('pbf');
var VectorTile = require('vector-tile').VectorTile;
var bigTile = process.argv[2];
//var outDir = process.argv[3];
var mbToken = 'sk.eyJ1IjoibGFuZHBsYW5uZXIiLCJhIjoiY2ltcjB0MmozMDB0MHY5a2t5c2Fsb3Q0diJ9.3qyTzT995P_Fo1fJ2tyr6A';
var mbUrlBase = 'http://a.tiles.mapbox.com/v4/mapbox.mapbox-streets-v7/';
var mbUrlSuffix = '.vector.pbf?access_token=' + mbToken;
var x = JSON.parse(bigTile)[0];
var y = JSON.parse(bigTile)[1];
var z = JSON.parse(bigTile)[2];
var getTile = request({url: mbUrlBase + z + '/' + x + '/' + y + mbUrlSuffix, gzip: true, encoding: null}, function (error, response, body) {
if (error) {
console.error('encountered error', error instanceof Error ? error.stack : error);
} else if (response.statusCode === 429) {
console.log('error 429');
} else if (response.statusCode !== 200) {
console.error('non-200 status code: ' + response.statusCode);
} else {
var buf = new Protobuf(body);
var vt = new VectorTile(buf);
var layer = vt.layers['water'];
if (layer && layer.length > 0) {
var waterSet = {"type":"FeatureCollection","features":[]};
for (var i = 0; i < layer.length; i++) {
var feature = layer.feature(i).toGeoJSON(x,y,z);
waterSet.features.push(feature);
}
fs.writeFile('osm_water_' + x + '_' + y + '_' + z + '.geojson', JSON.stringify(waterSet), 'utf-8');
console.log('got tile ' + bigTile);
}
else {
console.log('no water features at tile {' + z + '}/{' + x + '}/{' + y + '}')
}
}
});
getTile;
{
"name": "water",
"version": "2.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "vtcraghead@gmail.com",
"license": "ISC",
"dependencies": {
"pbf": "^1.3.5",
"request": "^2.69.0",
"turf": "^2.0.2",
"vector-tile": "^1.2.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment