我有sqlite3數據庫的位置有一個經度值和一個經度值。我想使用SELECT語句來獲取特定半徑內的位置。iOS - 用「<」運算符不起作用的Sqlite3查詢
我試圖實現一個如下所述:http://www.thismuchiknow.co.uk/?p=71及其所有工作正常,如果我的查詢是這樣的:
"SELECT pk FROM location WHERE distance(latitude, longitude, '%d', '%d') > 100"
,但如果我使用了「<」操盤手「 - >」,該聲明無法執行,我得到sqlite3_errmsg(數據庫)的「未知錯誤」。我真的不知道爲什麼使用另一個操作符會導致錯誤。任何人有想法?
我的代碼:
NSMutableArray *resultsArray = [[NSMutableArray alloc] init];
self.results = resultsArray;
[resultsArray release];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"Locations.sqlite"];
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
sqlite3_create_function(database, "distance", 4, SQLITE_UTF8, NULL, &distanceFunc, NULL, NULL);
double vLongitude;
double vLatitude;
vLongitude = 8.683;
vLatitude = 50.117;
sql = [[NSString stringWithFormat:@"SELECT pk FROM location WHERE distance(latitude, longitude, '%d', '%d') < 50", vLatitude, vLongitude]cStringUsingEncoding:NSUTF8StringEncoding];
sqlite3_stmt *statement;
if(sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK){
while(sqlite3_step(statement) == SQLITE_ROW) {
//the second parameter indicates the column index to the result set
int primary_key = sqlite3_column_int(statement, 0);
Location *loc = [[Location alloc] initWithPrimaryKey:primary_key database:database];
[results addObject:loc];
[loc release];
}
}
printf("could not prepare statemnt: %s\n", sqlite3_errmsg(database));
sqlite3_finalize(statement);
}
else {
sqlite3_close(database);
NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(database));
}
searchResultsController.results = self.results;
,並從上面的鏈接距離函數:
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);
}
我試過%f而不是%d,它的工作正常。用%d表示距離的結果,其中距離5000英里的點只有100英里的距離。非常感謝你! – soet 2012-01-24 16:14:11