使用SQLITE的Long Lat coord之间的距离

时间:2010-05-28 01:39:29

标签: iphone sqlite distance latitude-longitude cllocation

我有一个带有长商店的sqlite数据库,我想找到最近的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读入数组,然后对数组进行排序。您是否建议采用上述方法?这样效率更高吗?

  3. 最后,如果有人有更好的方法来获得最近的5家商店,那就爱听。

2 个答案:

答案 0 :(得分:6)

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

这是我以前用过的一个:

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

答案 1 :(得分:0)

你必须只运行一次每个元素,因此复杂性相当好。 你需要一种固定大小的Deque-container,一种链表或一个固定大小的数组,固定大小为5,你想从每个点获得的商店数量。总是添加与Deque最小距离的商店。在您的数据库中运行后,您的deque中最近有5家商店。

相关问题