Skip to content

Instantly share code, notes, and snippets.

@Krizz
Last active February 13, 2025 01:07
Function source to dynamically load tiles from tables.
CREATE OR REPLACE FUNCTION function_zxy_query(z integer, x integer, y integer, query_params json)
RETURNS bytea AS $$
DECLARE
mvt bytea;
table_name text;
sql_query text;
BEGIN
-- Extract the table name from query_params
table_name := (query_params->>'table_name');
-- Construct the SQL query dynamically using the extracted table name
EXECUTE format('
SELECT ST_AsMVT(tile, ''function_zxy_query'', 4096, ''geometry'')
FROM (
SELECT ST_AsMVTGeom(
ST_Transform(ST_CurveToLine(geometry), 3857),
ST_TileEnvelope(%L, %L, %L),
4096, 64, true) AS geometry,
jsonb_build_object(
''id'', properties->>''id''
) AS properties
FROM %I
WHERE geometry && ST_Transform(ST_TileEnvelope(%L, %L, %L), 4326)
) as tile
WHERE geometry IS NOT NULL;
', z, x, y, table_name, z, x, y) INTO mvt;
RETURN mvt;
END
$$ LANGUAGE plpgsql IMMUTABLE STRICT PARALLEL SAFE;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment