]> git.openstreetmap.org Git - rails.git/blob - db/functions/maptile.c
Avoid using live models in old migrations
[rails.git] / db / functions / maptile.c
1 #include <math.h>
2 #include <postgres.h>
3 #include <fmgr.h>
4
5 Datum
6 maptile_for_point(PG_FUNCTION_ARGS)
7 {
8    double lat = PG_GETARG_INT64(0) / 10000000.0;
9    double lon = PG_GETARG_INT64(1) / 10000000.0;
10    int zoom = PG_GETARG_INT32(2);
11    double scale = pow(2, zoom);
12    double r_per_d = M_PI / 180;
13    unsigned int x;
14    unsigned int y;
15
16    x = floor((lon + 180.0) * scale / 360.0);
17    y = floor((1 - log(tan(lat * r_per_d) + 1.0 / cos(lat * r_per_d)) / M_PI) * scale / 2.0);
18
19    PG_RETURN_INT32((x << zoom) | y);
20 }
21
22 PG_FUNCTION_INFO_V1(maptile_for_point);
23
24 /*
25  * To bind this into PGSQL, try something like:
26  *
27  * CREATE FUNCTION maptile_for_point(int8, int8, int4) RETURNS int4
28  *  AS '/path/to/rails-port/db/functions/libpgosm', 'maptile_for_point'
29  *  LANGUAGE C STRICT;
30  *
31  * (without all the *s)
32  */
33
34 #ifdef PG_MODULE_MAGIC
35 PG_MODULE_MAGIC;
36 #endif