开发者

How to match current location coordinates with coordinates saved in database

I have a database with coordinates of different places. Whenever a user comes to the place saved in database, a window should pop up reminding the user of coming to that place.

For that I continuously need to check the current location coordinates with the coordinates saved in database. And when a match is found, the popup window should displayed.

I can use CoreLocati开发者_开发百科onManager to get current location. But how do I implement this code?


you need to create sqlite function for distance

sqlite3_create_function(database, "distance", 4, SQLITE_UTF8, NULL, &distanceFunc, NULL, NULL);

this takes 4 arguments latitude1, longitude1, latitude2, longitude2. This will create a function in database, which will point to following function.

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
double distance = fabs(acos(sin(lat1rad) * sin(lat2rad) + cos(lat1rad) * cos(lat2rad) * cos(DEG2RAD(lon2) - DEG2RAD(lon1))) * 6378.1);
sqlite3_result_double(context, distance);
}

Now you can fire query,

NSString stringWithFormat[@"select distance(latitude,longitude,%@,%@) from table", currentLatitude, currentLongitude];

Where "latitude" and "longitude" are fields of table, and "currentLatitude" and "currentLongitude" are current location coordintates.

you will get distance between your saved coordinates in database and current location coordinates.

Hope it helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜