|
| 1 | +-------------------------------------------------------------------------------- |
| 2 | +-- From https://github.com/openstreetmap/openstreetmap-website/blob/af273f5d6ae160de0001ce1ac0c087d92a2463c6/db/functions/functions.sql |
| 3 | +-- SQL versions of the C database functions. |
| 4 | +-- |
| 5 | +-- Pure pl/pgsql versions are *slower* than the C versions, and not recommended |
| 6 | +-- for production use. However, they are significantly easier to install, and |
| 7 | +-- require fewer dependencies. |
| 8 | +-------------------------------------------------------------------------------- |
| 9 | + |
| 10 | +-- tile_for_point function returns a Morton-encoded integer representing a z16 |
| 11 | +-- tile which contains the given (scaled_lon, scaled_lat) coordinate. Note that |
| 12 | +-- these are passed into the function as (lat, lon) and should be scaled by |
| 13 | +-- 10^7. |
| 14 | +-- |
| 15 | +-- The Morton encoding packs two dimensions down to one with fairly good |
| 16 | +-- spatial locality, and can be used to index points without the need for a |
| 17 | +-- proper 2D index. |
| 18 | +CREATE OR REPLACE FUNCTION tile_for_point(scaled_lat int4, scaled_lon int4) |
| 19 | + RETURNS int8 |
| 20 | + AS $$ |
| 21 | +DECLARE |
| 22 | + x int8; -- quantized x from lon, |
| 23 | + y int8; -- quantized y from lat, |
| 24 | +BEGIN |
| 25 | + x := round(((scaled_lon / 10000000.0) + 180.0) * 65535.0 / 360.0); |
| 26 | + y := round(((scaled_lat / 10000000.0) + 90.0) * 65535.0 / 180.0); |
| 27 | + |
| 28 | + -- these bit-masks are special numbers used in the bit interleaving algorithm. |
| 29 | + -- see https://graphics.stanford.edu/~seander/bithacks.html#InterleaveBMN |
| 30 | + -- for the original algorithm and more details. |
| 31 | + x := (x | (x << 8)) & 16711935; -- 0x00FF00FF |
| 32 | + x := (x | (x << 4)) & 252645135; -- 0x0F0F0F0F |
| 33 | + x := (x | (x << 2)) & 858993459; -- 0x33333333 |
| 34 | + x := (x | (x << 1)) & 1431655765; -- 0x55555555 |
| 35 | + |
| 36 | + y := (y | (y << 8)) & 16711935; -- 0x00FF00FF |
| 37 | + y := (y | (y << 4)) & 252645135; -- 0x0F0F0F0F |
| 38 | + y := (y | (y << 2)) & 858993459; -- 0x33333333 |
| 39 | + y := (y | (y << 1)) & 1431655765; -- 0x55555555 |
| 40 | + |
| 41 | + RETURN (x << 1) | y; |
| 42 | +END; |
| 43 | +$$ LANGUAGE plpgsql IMMUTABLE; |
0 commit comments