Distance function for sqlite

Posted on October 25, 2008 by Dave

As part of an iPhone SDK project, I have an sqlite database with a table full of geographic locations, each stored as a latitude and longitude value in degrees. I wanted to be able to perform an SQL SELECT on this table and ORDER BY each row’s distance from an arbitrary point. I’ve achieved this by defining a custom sqlite function. This article contains the code for the function, together with instructions on using it.

Here’s the function, together with a convenience macro to convert from degrees to radians. This function is based on an online distance calculator I found which makes use of the spherical law of cosines.


#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-null
if (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 values
double 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 below
double 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 kilometres
sqlite3_result_double(context, acos(sin(lat1rad) * sin(lat2rad) + cos(lat1rad) * cos(lat2rad) * cos(DEG2RAD(lon2) - DEG2RAD(lon1))) * 6378.1);
}

This defines an SQL function distance(Latitude1, Longitude1, Latitude2, Longitude2), which returns the distance (in kilometres) between two points.

To use this function, add the code above to your Xcode project, and then add this line immediately after you call sqlite3_open:


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

…where sqliteDatabasePtr is the database pointer returned by your call to sqlite3_open.

Assuming you have a table called Locations, with columns called Latitude and Longitude (both of type double) containing values in degrees, you can then use this function in your SQL like this:


SELECT * FROM Locations ORDER BY distance(Latitude, Longitude, 51.503357, -0.1199)

This example orders the locations in your database based on how far away they are from the London Eye, which is at 51.503357, -0.1199.

Distance function for sqlite的更多相关文章

  1. Manhattan distance(for lab)

    Input four integer x1, y1, x2, y2, which is mean that the coordinates of two points A(x1, y1), B(x2, ...

  2. SQLite Learning、SQL Query Optimization In Multiple Rule

    catalog . SQLite简介 . Sqlite安装 . SQLite Programing . SQLite statements 1. SQLite简介 SQLite是一款轻型的数据库,是遵 ...

  3. Android-adb 常用命令 和 sqlite

    Android开发环境中,ADB是我们进行Android开发经常要用的调试工具,它的使用当然是我们Android开发者必须要掌握的. ADB概述 Android Debug Bridge,Androi ...

  4. sqlite详细介绍

    ------------------------------------------------------------------------------SQLite简介-------------- ...

  5. SQLite 语法(http://www.w3cschool.cc/sqlite/sqlite-syntax.html)

    SQLite 语法 SQLite 是遵循一套独特的称为语法的规则和准则.本教程列出了所有基本的 SQLite 语法,向您提供了一个 SQLite 快速入门. 大小写敏感性 有个重要的点值得注意,SQL ...

  6. Brute-forced Euclid Distance Transform

    Sepearable 2D EDT, going to extend to 3D in order to calculate the Signed Distance Function(Field) C ...

  7. 相似性 similarity | Pearson | Spearman | p-value | 相关性 correlation | 距离 distance | distance measure

    这几个概念不能混淆,估计大部分人都没有完全搞懂这几个概念. 看下这个,非常有用:Interpret the key results for Correlation euclidean | maximu ...

  8. Signed Distance Field Technique

    [Distance Field Technique] 一种小纹理高清放大的技术. A distance field is generated from a high resolution image, ...

  9. java sqlite配置和自定义函数

    资源 jetty Jetty Downloads地址 sqlite sqlite JDBC Driver 地址:bitbucket代码托管 和 Github代码托管 jetty配置sqlite 在je ...

随机推荐

  1. Traffic Network in Numazu

    Traffic Network in Numazu 题目描述 Chika is elected mayor of Numazu. She needs to manage the traffic in ...

  2. CF-595

    题目传送门 A .Yet Another Dividing into Teams sol:原先是用比较复杂的方法来解的,后来学弟看了一眼,发现不是1就是2,当出现两个人水平相差为1就分成两组,1组全是 ...

  3. 从二叉搜索树到AVL树再到红黑树 B树

    这几种树都属于数据结构中较为复杂的,在平时面试中,经常会问理解用法,但一般不会问具体的实现,所以今天来梳理一下这几种树之间的区别与联系,感谢知乎用户@Cailiang,这篇文章参考了他的专栏. 二叉查 ...

  4. CentOS-TFTP服务搭建

    title date tags layout CentOS6.5 TFTP搭建 2018-08-26 Centos6.5服务器搭建 post 1.安装TFTP服务 yum install tftp-s ...

  5. 2)PHP代码运行过程

    https://zhidao.baidu.com/question/544575728.html

  6. 在virtualenv中安装NumPy、 SciPy、 scikit-learn、 matplotlib

    首先要进入对应的虚拟环境 然后安装包    这里把安装源改成使用豆瓣的源进行下载  这样的话 下载速度会快很多   安装numpy包 pip install numpy -i https://pypi ...

  7. deeplearning.ai 神经网络和深度学习 week4 深层神经网络

    1. 计算深度神经网络的时候,尽量向量化数据,不要用for循环.唯一用for循环的地方是依次在每一层做计算. 2. 最常用的检查代码是否有错的方法是检查算法中矩阵的维度. 正向传播: 对于单个样本,第 ...

  8. VisionPro 图标工具说明

  9. CSAPC08台湾邀请赛_T1_skyline

    题目链接:CSAPC08台湾邀请赛_T1_skyline 题目描述 一座山的山稜线由许多片段的45度斜坡构成,每一个片段不是上坡就是下坡. / /​ * / ​/ * /  // ​/ // / 在我 ...

  10. 吴裕雄--天生自然KITTEN编程:青蛙答题过河