Skip to content

Instantly share code, notes, and snippets.

@nim4n136
Created January 17, 2021 08:15
Show Gist options
  • Save nim4n136/4a742def618c275fa03c9916f495fd0b to your computer and use it in GitHub Desktop.
Save nim4n136/4a742def618c275fa03c9916f495fd0b to your computer and use it in GitHub Desktop.
Function Bbox Tile Postgis
/******************************************************************************
### TileBBox ###
Given a Web Mercator tile ID as (z, x, y), returns a bounding-box
geometry of the area covered by that tile.
__Parameters:__
- `integer` z - A tile zoom level.
- `integer` x - A tile x-position.
- `integer` y - A tile y-position.
- `integer` srid - SRID of the desired target projection of the bounding
box. Defaults to 3857 (Web Mercator).
__Returns:__ `geometry(polygon)`
******************************************************************************/
create or replace function TileBBox (z int, x int, y int, srid int = 3857)
returns geometry
language plpgsql immutable as
$func$
declare
max numeric := 20037508.34;
res numeric := (max*2)/(2^z);
bbox geometry;
begin
bbox := ST_MakeEnvelope(
-max + (x * res),
max - (y * res),
-max + (x * res) + res,
max - (y * res) - res,
3857
);
if srid = 3857 then
return bbox;
else
return ST_Transform(bbox, srid);
end if;
end;
$func$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment