数据库中查询,两个经纬度之间的距离代码
double radians(double degrees) { return degrees * M_PI / 180.0; } - (void)testDistance { FMDatabase *db = [FMDatabase databaseWithPath:_writableDBPath]; if (![db open]) { return; } [db makeFunctionNamed:@"distance" maximumArguments:4 withBlock:^(sqlite3_context *context, int argc, sqlite3_value **argv) { double values[4]; // get the double values for the four arguments for (int i = 0; i < 4; i++) { int dataType = sqlite3_value_numeric_type(argv[i]); if (dataType == SQLITE_INTEGER || dataType == SQLITE_FLOAT) { values[i] = sqlite3_value_double(argv[i]); } else { sqlite3_result_null(context); return; } } // let's give those values meaningful variable names double lat = radians(values[0]); double lng = radians(values[1]); double lat2 = radians(values[2]); double lng2 = radians(values[3]); // calculate the distance double result = 6371.393 * acos(cos(lat2) * cos(lat) * cos(lng2 - lng) + sin(lat2) * sin(lat)); sqlite3_result_double(context, result); }]; int rowCount = 0; FMResultSet *rs = [db executeQuery:@"SELECT *,distance(lat,lng,34.27344,108.95996) AS distance FROM hotel WHERE cityId = 10 AND lat > 33.27344 AND lat < 35.27344 AND lng > 107.95996 AND lng < 109.95996 ORDER BY distance ASC LIMIT 10"]; while ([rs next]) { rowCount++; NSLog(@"Does %@,%@ ", [rs stringForColumnIndex:1],[rs stringForColumn:@"distance"]); } }