I've a problem. I want to get the nearest points on google map in android app. Different points/coordinates are stored in sqlite database. And I have to get the nearest 5 from them. The Query I'm using is:
SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < 25 ORDER BY distance LIMIT 0 , 5;
But I'm getting an error i.e. "no such function: acos exists".
What will be its proper solution
SQLite doesn't support any trigonometric functions by default, so you can't use them in SQL queries.
You can either fetch the list of coordinates and process it in application code, or you can try and expose Java's trigonometric functions in SQLite with user defined functions (see How can I create a user-defined function in SQLite?).
You can create extension in C that implements trigonometric functions, for example:
/* sql_trig.c */
#include "sqlite3ext.h"
SQLITE_EXTENSION_INIT1;
#include <stdlib.h>
/* this bit is required to get M_PI out of MS headers */
#if defined( _WIN32 )
#define _USE_MATH_DEFINES
#endif /* _WIN32 */
#include <math.h>
#define RADIANS(d) (( d / 180.0 ) * M_PI)
static void sql_trig_sin( sqlite3_context *ctx, int num_values, sqlite3_value **values )
{
double a = RADIANS(sqlite3_value_double( values[0] ));
sqlite3_result_double( ctx, sin( a ) );
}
static void sql_trig_cos( sqlite3_context *ctx, int num_values, sqlite3_value **values )
{
double a = RADIANS(sqlite3_value_double( values[0] ));
sqlite3_result_double( ctx, cos( a ) );
}
static void sql_trig_acos( sqlite3_context *ctx, int num_values, sqlite3_value **values )
{
double a = sqlite3_value_double( values[0] );
sqlite3_result_double( ctx, acos( a ) );
}
static void sql_trig_radians( sqlite3_context *ctx, int num_values, sqlite3_value **values )
{
sqlite3_result_double( ctx, RADIANS(sqlite3_value_double( values[0] ) ));
}
int sqlite3_extension_init( sqlite3 *db, char **error, const sqlite3_api_routines *api )
{
SQLITE_EXTENSION_INIT2(api);
sqlite3_create_function( db, "sin",1,
SQLITE_UTF8, NULL, &sql_trig_sin, NULL, NULL );
sqlite3_create_function( db, "cos",1,
SQLITE_UTF8, NULL, &sql_trig_cos, NULL, NULL );
sqlite3_create_function( db, "acos",1,
SQLITE_UTF8, NULL, &sql_trig_acos, NULL, NULL );
return SQLITE_OK;
}
Now you can compile it as a shared library:
$ gcc -c -fPIC sql_trig.c
$ ld -shared -o sql_trig.so sql_trig.o -lm
and load it with SELECT load_extension('./sql_trig.so')