-
Notifications
You must be signed in to change notification settings - Fork 1
/
mvt.js
232 lines (221 loc) · 7.26 KB
/
mvt.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
// based on https://raw.githubusercontent.com/tobinbradley/dirt-simple-postgis-http-api/master/routes/mvt.js
const sqlTableName = require('./utils/sqltablename.js');
const dbutils = require('./utils/dbutils.js');
const sm = require('@mapbox/sphericalmercator');
const merc = new sm({
size: 256
})
function toBoolean(value) {
if (!value) {
return false;
}
if (typeof value === 'string'){
if (value.trim() === '') {
return false;
} else if (Number(value) === NaN) {
switch (value.toLowerCase().trim()) {
case 'no':
case 'false':
case 'n':
case 'f':
return false;
default:
return true;
}
} else {
return Number(value) !== 0;
}
}
if (Number(value)!== NaN) {
return Number(value) !== 0;
}
return true;
}
function queryColumnsNotNull(query) {
const queryColumns = query.columns;
const includeNulls = toBoolean(query.include_nulls);
if (!includeNulls && queryColumns) {
return ` and (${queryColumns.split(',').map((column, index)=>`$(column${index}:name) is not null`).join(' or ')})`
}
return ''
}
const sql2 = (params, query) => {
let bounds = merc.bbox(params.x, params.y, params.z, false, '900913')
return `
SELECT ST_AsMVT(q, '${params.table}', 4096, 'geom')
FROM
(SELECT ${query.columns ? `${query.columns},` : ''}
ST_AsMVTGeom(
ST_Transform(${query.geom_column}, 3857),
ST_MakeBox2D(ST_Point(${bounds[0]}, ${bounds[1]}), ST_Point(${bounds[2]}, ${bounds[3]}))
) geom
FROM
(SELECT ${query.columns ? `${query.columns},` : ''} ${query.geom_column}, srid
FROM
${sqlTableName(params.table)},
(SELECT ST_SRID(${query.geom_column}) AS srid FROM ${sqlTableName(params.table)}
WHERE ${query.geom_column} is not null LIMIT 1) a
WHERE
${query.geom_column} is not null AND
ST_transform(
ST_MakeEnvelope(${bounds.join()}, 3857),
srid
) && ${query.geom_column}
${queryColumnsNotNull(query)}
-- Optional Filter
${query.filter ? `AND ${query.filter}` : ''}
) r
) q
`
} // TODO, use sql place holders $1, $2 etc. instead of inserting user-parameters into query
let sql = (query) => {
return `
SELECT ST_AsMVT(q, $(table.fullname), 4096, 'geom')
FROM
(SELECT $(columns:name),
ST_AsMVTGeom(
ST_Transform($(geomcolumn:name), 3857),
ST_MakeBox2D(ST_Point($(bounds0), $(bounds1)), ST_Point($(bounds2), $(bounds3)))
) geom
FROM
(SELECT $(columns:name), $(geomcolumn:name), srid
FROM
$(table.schema:name).$(table.name:name),
(SELECT ST_SRID($(geomcolumn:name)) AS srid FROM $(table.schema:name).$(table.name:name)
WHERE $(geomcolumn:name) is not null LIMIT 1) a
WHERE
$(geomcolumn:name) is not null AND
ST_transform(
ST_MakeEnvelope($(bounds:csv), 3857),
srid
) && $(geomcolumn:name)
${queryColumnsNotNull(query)}
) r limit 2000000
) q
`
}
module.exports = function(app, pool, cache) {
let cacheMiddleWare = async(req, res, next) => {
if (!cache) {
next();
return;
}
const cacheDir = `${req.params.datasource}/mvt/${req.params.z}/${req.params.x}/${req.params.y}`;
const key = ((req.query.geom_column?req.query.geom_column:'geom') + (req.query.columns?','+req.query.columns:'')) + (toBoolean(req.query.include_nulls)?'_includenulls':'')
.replace(/[\W]+/g, '_');
const mvt = await cache.getCachedFile(cacheDir, key);
if (mvt) {
console.log(`cache hit for ${cacheDir}?${key}`);
if (mvt.length === 0) {
res.status(204)
}
res.header('Content-Type', 'application/x-protobuf').send(mvt);
return;
} else {
res.sendResponse = res.send;
res.send = (body) => {
if (res.statusCode >= 200 && res.statusCode < 300) {
cache.setCachedFile(cacheDir, key, body);
}
res.sendResponse(body);
}
next();
}
}
/**
* @swagger
*
* /data/{datasource}/mvt/{z}/{x}/{y}:
* get:
* description: get mapbox vector tile (mvt)
* tags: ['geodata']
* produces:
* - application/x-protobuf
* parameters:
* - name: datasource
* description: name of postgis datasource
* in: path
* required: true
* type: string
* - name: z
* description: zoom level of tile
* in: path
* required: true
* type: number
* - name: x
* description: x value (column number) of tile
* in: path
* required: true
* type: number
* - name: y
* description: y value (row number) of tile
* in: path
* required: true
* type: number
* - name: geom_column
* description: name of geometry column (default 'geom')
* in: query
* required: false
* - name: columns
* description: optional comma seperated list of attribute columns to be added to the mvt geometries
* in: query
* required: false
* type: string
* - name: include_nulls
* description: 'optional parameter to include geometries where all attribute columns are null (default: false)'
* in: query
* required: false
* type: string
* responses:
* 200:
* description: vector tile
* 204:
* description: no data (empty tile)
* 422:
* description: invalid datasource or columnname
*/
app.get('/data/:datasource/mvt/:z/:x/:y', cacheMiddleWare, async (req, res)=>{
if (!req.query.geom_column) {
req.query.geom_column = 'geom'; // default
}
req.params.table = req.params.datasource;
try {
let bounds = merc.bbox(req.params.x, req.params.y, req.params.z, false, '900913');
let sqlString = sql(req.query);
let sqlParams = {
table: dbutils.splitSchemaTable(req.params.table),
columns: req.query.columns.split(','),
geomcolumn: req.query.geom_column,
bounds: bounds,
bounds0: bounds[0],
bounds1: bounds[1],
bounds2: bounds[2],
bounds3: bounds[3]
};
req.query.columns.split(',').forEach((column, index)=>{
sqlParams[`column${index}`] = column;
})
const result = await pool.one(sqlString, sqlParams);
const mvt = result.st_asmvt
if (mvt.length === 0) {
res.status(204)
}
res.header('Content-Type', 'application/x-protobuf').send(mvt);
} catch(err) {
console.log(err);
let status = 500;
switch (err.code) {
case '42P01':
// table does not exist
status = 422;
break;
case '42703':
// column does not exist
status = 422;
break;
default:
}
res.status(status).json({error:err.message})
}
})
}