1

我已经实现了出色的 Dave Addey 提供的算法,以使用“余弦球面定律”公式计算两个坐标之间的距离(这是原始链接)。这就是我打算在查询中使用函数调用的方式:

NSString *SQLQuery= [NSString stringWithFormat: @"SELECT distance(lat, lon, '%f', '%f') as distance, * FROM table WHERE distance < %f", coord.latitude, coord.longitude, distance/1000.0];

问题是我可以正确过滤半径为 1 公里的结果,但是当我尝试访问“距离”列时,它总是返回 0。我使用的是 FMDatabase,但直接调用 sqlite3 ( [resultset doubleForColumnIndex: 0]) 并不能修复问题。

这是用于声明函数的代码(我也尝试直接调用 sqlite3):

    [database makeFunctionNamed:@"distance"
               maximumArguments:4
                      withBlock: ^( 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
                          double distance = acos(sin(lat1rad) * sin(lat2rad) + cos(lat1rad) * cos(lat2rad) * cos(DEG2RAD(lon2) - DEG2RAD(lon1))) * 6378.1;
                          sqlite3_result_double(context, distance);
                      }];

有什么线索吗?

4

1 回答 1

0

SQL Query 的构建方式有错误,应该是:

@"SELECT * FROM (SELECT distance(lat, lon, %f, %f) as distance, * FROM table) WHERE distance < %f ORDER BY distance DESC"

(有关详细信息,请参阅问题的评论)

于 2014-09-05T12:59:27.353 回答