2013年7月2日 星期二

sqlite 3 自定函数方法

关键字 sqlite3_create_function

这方法 ios 应该可以接受

来自

http://www.thismuchiknow.co.uk/?p=71

使用方法

sqlite3_create_function(sqliteDatabasePtr, "distance", 4, SQLITE_UTF8, NULL, &distanceFunc, NULL, NULL);

记得先定义函数

#define DEG2RAD(degrees) (degrees * 0.01745327) // degrees * pi over 180

static void distanceFunc(sqlite3_context *context, int argc, sqlite3_value **argv){// check that we have four arguments (lat1, lon1, lat2, lon2)assert(argc == 4);// check that all four arguments are non-nullif (sqlite3_value_type(argv[0]) == SQLITE_NULL || sqlite3_value_type(argv[1]) == SQLITE_NULL || sqlite3_value_type(argv[2]) == SQLITE_NULL || sqlite3_value_type(argv[3]) == SQLITE_NULL) {sqlite3_result_null(context);return;}// get the four argument valuesdouble lat1 = sqlite3_value_double(argv[0]);double lon1 = sqlite3_value_double(argv[1]);double lat2 = sqlite3_value_double(argv[2]);double lon2 = sqlite3_value_double(argv[3]);// convert lat1 and lat2 into radians now, to avoid doing it twice belowdouble lat1rad = DEG2RAD(lat1);double lat2rad = DEG2RAD(lat2);// apply the spherical law of cosines to our latitudes and longitudes, and set the result appropriately// 6378.1 is the approximate radius of the earth in kilometressqlite3_result_double(context, acos(sin(lat1rad) * sin(lat2rad) + cos(lat1rad) * cos(lat2rad) * cos(DEG2RAD(lon2) - DEG2RAD(lon1))) * 6378.1);}

沒有留言: