テーブルに対してSQL SELECT (sqlite)を実行し、任意の点から各行の距離でORDER BYを実行できるようにしたい
-
26-09-2019 - |
質問
私は、地理的位置の完全なテーブルを含む sqlite データベースを持っており、それぞれが度単位の緯度と経度の値として保存されています。このテーブルに対して SQL SELECT を実行し、任意の点から各行の距離で ORDER BY を実行できるようにしたいと考えていました。以下に定義されているカスタム sqlite 関数 ( distanceFunc ) を使用してこれを実現しました。
以下にその関数と、度からラジアンに変換する便利なマクロを示します。この関数は、余弦の球面法則を利用したオンライン距離計算機に基づいています。
http://en.wikipedia.org/wiki/Spherical_law_of_cosines
「球面三角法における余弦の法則(辺の余弦定理とも呼ばれる)は、球面三角形の辺と角度に関する定理であり、平面三角法の通常の余弦の法則に似ています。」
#define DEG2RAD(degrees) (degrees * 0.01745327) // degrees * pi over 180
(Location.m) の「 distanceFunc 」
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);
}
次のように「Location.m」にもあるメソッド「getDistanceBetweenLongLat」を呼び出します。
私の (AppDelegate.m) で使用されているもの:
Location *location = [[Location alloc] init];
location.latitude = -37.1134; //double property
location.longitude = 145.4254; //double property
[location getDistanceBetweenLongLat:[self dbPath]];
(Location.m) の「getDistanceBetweenLongLat」メソッド:
- (void) getDistanceBetweenLongLat:(NSString *)dbPath {
AppDelegate *_ad = (AppDelegate *)[[UIApplication sharedApplication] delegate];
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
sqlite3_create_function(database, "distance", 4, SQLITE_UTF8, NULL, &distanceFunc, NULL, NULL);
const char *sql = "select * from locations order by distance(latitude, longitude, ?, ?)";
sqlite3_stmt *selectstmt;
sqlite3_bind_double(selectStmt, 1, latitude);
sqlite3_bind_double(selectStmt, 2, longitude);
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
NSInteger primaryKey = sqlite3_column_int(selectstmt, 0);
Location *location = [[Location alloc] initWithPrimaryKey:primaryKey];
location.latitude = sqlite3_column_double(selectstmt, 1);
location.longitude = sqlite3_column_double(selectstmt, 2);
location.title = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 3)];
location.street1 = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 4)];
location.street2 = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 5)];
location.suburb = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 6)];
NSInteger postCodeItem = sqlite3_column_int(selectstmt, 7);
location.postcode = postCodeItem;
location.isDirty = NO;
[_ad.locations addObject:location];
[location release];
}
}
} else {
//Even though the open call failed, close the database connection to release all the memory.
sqlite3_close(database);
}
}
これは「 distanceFunc 」を正常に呼び出しています。ただし、4 つの引数すべてが null でないことを確認するステートメントに到達すると、すべて null として返されます。
ただし、上記の SQL ステートメントを次のように変更すると、次のようになります。
const char *sql = "select * from locations order by distance(latitude, longitude, '?', '?')"; //single quotes added
4 つの引数は null として返されません。しかし、最後の 2 つの引数の値は、次のようにあるべきときに 0 になりますよね。
location.latitude = -37.1134; //double property
location.longitude = 145.4254; //double property:
(Location.m) の「 distanceFunc 」から:
double lat1 = sqlite3_value_double(argv[0]); // -17.7699 from 1st result in Locations table
double lon1 = sqlite3_value_double(argv[1]); // 245.1103 from 1st result in Locations table
double lat2 = sqlite3_value_double(argv[2]); // 0
double lon2 = sqlite3_value_double(argv[3]); // 0
表示する初期データを取得するためにほぼ同じ方法を使用しており、その特定の配列には問題なく値が設定されています。今回は、代わりに距離順に並べられた結果を UITableView で表示できるように、location 配列 (_ad.locations 内) に含めたいだけです。
注記:使用される「 distanceFunc 」は、次のリンクにもあります。 http://www.thismuchiknow.co.uk/?p=71&cpage=1#comment-30834
解決
私はバリエーションを使用します。ここで、latVal と longVal は現在の場所です。
NSString *sqlString = @"SELECT * FROM stores WHERE status = 1 AND distance(latitude, longitude, %f, %f, id) < 800";
sqlString = [NSString stringWithFormat:sqlString, latVal, longVal];
また、変数を使用して distanceFunc 内の距離値を読み取り、最後の 2 行を次のように変更します。
float val = acos(sin(lat1rad) * sin(lat2rad) + cos(lat1rad) * cos(lat2rad) * cos(DEG2RAD(lon2) - DEG2RAD(lon1))) * 6378.1;
distanceVal = (float)val;
sqlite3_result_double(context, val);
次に、一致に一致するオブジェクトに distanceVal を保存し、返されたアイテムに並べ替えを適用します。
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"distance" ascending:YES];
[ locations sortUsingDescriptors: [ NSArray arrayWithObject: sortDescriptor ] ];
[sortDescriptor release];