]> git.openstreetmap.org Git - rails.git/blob - db/functions/maptile.c
Use LoadFile(*DATA) to load the __DATA__ section as YAML
[rails.git] / db / functions / maptile.c
1 #ifndef USE_MYSQL
2 #ifndef USE_PGSQL
3 #error One of USE_MYSQL or USE_PGSQL must be defined
4 #endif
5 #endif
6
7 #include <math.h>
8
9 /* The real maptile-for-point functionality is here */
10
11 static long long internal_maptile_for_point(double lat, double lon, long long zoom)
12 {
13    double       scale = pow(2, zoom);
14    double       r_per_d = M_PI / 180;
15    unsigned int x;
16    unsigned int y;
17
18    x = floor((lon + 180.0) * scale / 360.0);
19    y = floor((1 - log(tan(lat * r_per_d) + 1.0 / cos(lat * r_per_d)) / M_PI) * scale / 2.0);
20
21    return (x << zoom) | y;
22 }
23
24 #ifdef USE_MYSQL
25 #ifdef USE_PGSQL
26 #error ONLY one of USE_MYSQL and USE_PGSQL should be defined
27 #endif
28
29 #include <my_global.h>
30 #include <my_sys.h>
31 #include <m_string.h>
32 #include <mysql.h>
33
34 my_bool maptile_for_point_init(UDF_INIT *initid, UDF_ARGS *args, char *message)
35 {
36    if ( args->arg_count != 3 ||
37         args->arg_type[0] != INT_RESULT ||
38         args->arg_type[1] != INT_RESULT ||
39         args->arg_type[2] != INT_RESULT )
40    {
41       strcpy( message, "Your maptile_for_point arguments are bogus!" );
42       return 1;
43    }
44
45    return 0;
46 }
47
48 void maptile_for_point_deinit(UDF_INIT *initid)
49 {
50    return;
51 }
52
53 long long maptile_for_point(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error)
54 {
55    double       lat = *(long long *)args->args[0] / 10000000.0;
56    double       lon = *(long long *)args->args[1] / 10000000.0;
57    long long    zoom = *(long long *)args->args[2];
58
59    return internal_maptile_for_point(lat, lon, zoom);
60 }
61 #endif
62
63 #ifdef USE_PGSQL
64 #ifdef USE_MYSQL
65 #error ONLY one of USE_MYSQL and USE_PGSQL should be defined
66 #endif
67
68 #include <postgres.h>
69 #include <fmgr.h>
70
71 Datum
72 maptile_for_point(PG_FUNCTION_ARGS)
73 {
74   double lat = PG_GETARG_INT64(0) / 10000000.0;
75   double lon = PG_GETARG_INT64(1) / 10000000.0;
76   int zoom = PG_GETARG_INT32(2);
77
78   PG_RETURN_INT32(internal_maptile_for_point(lat, lon, zoom));
79 }
80
81 PG_FUNCTION_INFO_V1(maptile_for_point);
82
83 /*
84  * To bind this into PGSQL, try something like:
85  *
86  * CREATE FUNCTION maptile_for_point(int8, int8, int4) RETURNS int4
87  *  AS '/path/to/rails-port/db/functions/libpgosm', 'maptile_for_point'
88  *  LANGUAGE C STRICT;
89  *
90  * (without all the *s)
91  */
92
93 #ifdef PG_MODULE_MAGIC
94 PG_MODULE_MAGIC;
95 #endif
96
97 #endif