Skip to content

Instantly share code, notes, and snippets.

@jleppert
Created December 1, 2016 01:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jleppert/db8707826ce77a3ec4d61ddf68e42603 to your computer and use it in GitHub Desktop.
Save jleppert/db8707826ce77a3ec4d61ddf68e42603 to your computer and use it in GitHub Desktop.
postgres lat/lon projection functions
CREATE OR REPLACE FUNCTION worldSize (maxZoom int, tileSize int)
RETURNS int AS $$
DECLARE
size int;
BEGIN
size := power(2, maxZoom) * tileSize;
RETURN size;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION xLng (x int, worldSize int)
RETURNS double precision AS $$
DECLARE
lng double precision;
BEGIN
lng := ((x * 360)::float / worldSize::float) - 180;
RETURN lng;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION yLat (y int, worldSize int)
RETURNS double precision AS $$
DECLARE
y2 double precision;
lat double precision;
BEGIN
y2 := 180::float - y * 360::float / worldSize::float;
lat := 360::float / pi() * atan(exp(y2 * pi() / 180::float)) - 90;
RETURN lat;
END;
$$ LANGUAGE plpgsql;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment