├── config.json.txt ├── package.json ├── README.md ├── LICENSE.txt └── index.js /config.json.txt: -------------------------------------------------------------------------------- 1 | { 2 | "port": 8124, 3 | "postgis": "postgres://login:password@server/database", 4 | "cache": "public, max-age=2629000", 5 | "layers": { 6 | "parcels": { 7 | "table": "tax_parcels", 8 | "geom_column": "the_geom", 9 | "property_columns": ["pid"], 10 | "maxzoom": 14, 11 | "minzoom": 14 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "pg-vector-tile-server", 3 | "version": "1.0.1", 4 | "description": "Converts PostGIS queries to pbf vector tiles.", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [ 10 | "postgis", 11 | "vector-tiles" 12 | ], 13 | "author": "Tobin Bradley", 14 | "license": "MIT", 15 | "dependencies": { 16 | "chokidar": "^1.4.3", 17 | "d3-queue": "^2.0.2", 18 | "geojson-vt": "^2.1.8", 19 | "hapi": "^13.0.0", 20 | "pg": "^4.4.6", 21 | "sphericalmercator": "^1.0.4", 22 | "squel": "^4.3.0", 23 | "vt-pbf": "^2.0.2" 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NOTE OF PROJECT ABANDONMENT 2 | 3 | I added PG to MVT as a service (in a much better/faster way) to [this project](https://github.com/tobinbradley/dirt-simple-postgis-http-api). 4 | 5 | 6 | ## PostGIS Vector Tile server 7 | 8 | 9 | 10 | PostGIS to Mapbox vector tiles (pbf) using the [vt-pbf](https://github.com/anandthakker/vt-pbf) and [geojson-vt](https://github.com/mapbox/geojson-vt) libraries. 11 | 12 | Credit to [Frank Rowe](http://frankrowe.org/posts/2015/03/17/postgis-to-protobuf.html) for the original idea. 13 | 14 | To get going: 15 | 16 | ``` bash 17 | npm install 18 | ``` 19 | 20 | Rename `config.js.txt` to `config.js` and edit the layers and Postgres connection info. 21 | 22 | ``` bash 23 | node . 24 | ``` 25 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015 Mecklenburg County GIS 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | var Hapi = require('hapi'), 2 | server = new Hapi.Server(), 3 | SphericalMercator = require('sphericalmercator'), 4 | sm = new SphericalMercator({ 5 | size: 256 6 | }), 7 | pg = require('pg'), 8 | squel = require('squel').useFlavour('postgres'), 9 | d3 = require('d3-queue'), 10 | fs = require('fs'), 11 | config = JSON.parse(fs.readFileSync('config.json', 'utf8')), 12 | zlib = require('zlib'), 13 | chokidar = require('chokidar'), 14 | vtpbf = require('vt-pbf'), 15 | geojsonVt = require('geojson-vt'); 16 | 17 | 18 | server.connection({ 19 | host: 'localhost', 20 | port: config.port, 21 | routes: { 22 | cors: true 23 | } 24 | }); 25 | 26 | 27 | // reload config file if it changes 28 | chokidar.watch('config.json').on('change', (event, path) => { 29 | config = JSON.parse(fs.readFileSync('config.json', 'utf8')) 30 | }); 31 | 32 | // Format SQL 33 | function formatSQL(table, geom_column, columns, bbox, simplify) { 34 | var sql= squel.select() 35 | .field('row_to_json(fc)') 36 | .from( 37 | squel.select() 38 | .field("'FeatureCollection' As type") 39 | .field("array_to_json(array_agg(f)) As features") 40 | .from( 41 | squel.select() 42 | .field("'Feature' As type") 43 | .field(`ST_AsGeoJSON(ST_transform(ST_Simplify(lg.${geom_column}, ${simplify}), 4326), 6)::json As geometry`) 44 | .field(`row_to_json((SELECT l FROM (SELECT ${columns.join(',')} ) As l)) As properties`) 45 | .from(`${table} As lg`) 46 | .where(`lg.${geom_column} && ST_Transform(ST_MakeEnvelope(${bbox.join(',')} , 4326), find_srid('', '${table}', '${geom_column}'))`) 47 | .limit(5000) 48 | , 'f') 49 | , 'fc'); 50 | 51 | return sql.toString(); 52 | } 53 | 54 | // Fetch GeoJSON 55 | function fetchGeoJSON(conn, sql, callback) { 56 | pg.connect(conn, function(err, client, done) { 57 | if (err) { 58 | callback(null, 'Error fetching client from pool.'); 59 | } else { 60 | client.query(sql, function(err, result) { 61 | done(); // call done to release the connection back to the pool 62 | if (err) { 63 | callback(null, 'SQL Error: ' + err + '\n'); 64 | } else { 65 | callback(null, result.rows[0].row_to_json); 66 | } 67 | }); 68 | } 69 | }); 70 | } 71 | 72 | // Get list of layers 73 | server.route({ 74 | method: 'GET', 75 | path: '/list', 76 | handler: function(request, reply) { 77 | var theList = ''; 78 | for (var key in config.layers) { 79 | theList += key + ' minzoom:' + config.layers[key].minzoom + ' maxzoom:' + config.layers[key].maxzoom + '\n'; 80 | } 81 | reply(theList); 82 | } 83 | }); 84 | 85 | // Tile canon 86 | server.route({ 87 | method: 'GET', 88 | path: '/{table}/{z}/{x}/{y}.pbf', 89 | handler: function(request, reply) { 90 | if (config.layers[request.params.table]) { 91 | if (config.layers[request.params.table].maxzoom >= parseInt(request.params.z) && config.layers[request.params.table].minzoom <= parseInt(request.params.z)) { 92 | var sql = formatSQL(config.layers[request.params.table].table, config.layers["parcels"].geom_column, config.layers["parcels"].property_columns, sm.bbox(request.params.x, request.params.y, request.params.z), config.layers["parcels"].simplify); 93 | var q = d3.queue(); 94 | q.defer(fetchGeoJSON, config.postgis, sql); 95 | q.await(function(error, GeoJSON) { 96 | if (typeof GeoJSON == 'object') { 97 | var tileindex = geojsonVt(GeoJSON); 98 | var tile = tileindex.getTile(parseInt(request.params.z, 10), parseInt(request.params.x, 10), parseInt(request.params.y)); 99 | // pass in an object mapping layername -> tile object 100 | var buff = vtpbf.fromGeojsonVt({ 101 | [request.params.table]: tile 102 | }); 103 | zlib.gzip(buff, function(err, pbf) { 104 | reply(pbf) 105 | .header('Content-Type', 'application/x-protobuf') 106 | .header('Content-Encoding', 'gzip') 107 | .header('Cache-Control', config.cache); 108 | }); 109 | } else { 110 | reply(GeoJSON); 111 | } 112 | }); 113 | } else { 114 | reply('Tile rendering error: this layer does not do tiles less than zoom level ' + config.layers[request.params.table].maxzoom); 115 | } 116 | } else { 117 | reply('Tile rendering error: this layer has no configuration.'); 118 | } 119 | } 120 | }); 121 | 122 | // Unleash the hounds 123 | server.start(function() { 124 | console.log('Server running at:', server.info.uri); 125 | }); 126 | --------------------------------------------------------------------------------