4

我有一个 sqlite db,里面有很长很长的商店,我想找出最近的 5 家商店。

所以下面的代码工作正常。

    if(sqlite3_prepare_v2(db, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {


    while (sqlite3_step(compiledStatement) == SQLITE_ROW) {

        NSString *branchStr = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
        NSNumber *fLat = [NSNumber numberWithFloat:(float)sqlite3_column_double(compiledStatement, 1)];
        NSNumber *fLong = [NSNumber numberWithFloat:(float)sqlite3_column_double(compiledStatement, 2)];

        NSLog(@"Address %@, Lat = %@, Long = %@", branchStr, fLat, fLong);
        CLLocation *location1 = [[CLLocation alloc] initWithLatitude:currentLocation.coordinate.latitude longitude:currentLocation.coordinate.longitude];
        CLLocation *location2 = [[CLLocation alloc] initWithLatitude:[fLat floatValue] longitude:[fLong floatValue]];

        NSLog(@"Distance i meters: %f", [location1 getDistanceFrom:location2]);
        [location1 release];
        [location2 release];
    }       
}

我知道从我所在的地方到每家商店的距离。我的问题是。

  1. 将距离放回sqlite行是否更好,当我通过数据库时我有该行。我怎么做?我是否使用 UPDATE 语句?有人有一段代码可以帮助我。

  2. 我可以将 sqlite 读入一个数组,然后对数组进行排序。你推荐这个而不是上述方法吗?这更有效吗?

最后,如果有人有更好的方法来获得最近的 5 家商店,我很乐意听到。

4

2 回答 2

6

在 SQL 中查找附近位置的最快方法是在 SQL 查询中使用 Haversine 公式。在 Google 上搜索 sqlite 和 Haversine,你会找到一个实现。

这是我以前用过的一个:

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

于 2010-06-01T11:11:28.980 回答
0

您只需遍历每个元素一次,因此复杂性相当好。你需要一种固定大小的Deque-container,一种链表或者固定大小的数组,大小固定为5,每个点你想要得到的店铺数量。始终添加与 Deque 距离最短的商店。运行完您的数据库后,您的双端队列中有最近的 5 家商店。

于 2010-06-01T11:12:16.713 回答