本文介绍了使用Core Data查找距离lat / long最近的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有Core Data数据库的iPhone应用程序,其中包含位置列表,每个位置都有纬度/经度坐标。我如何搜索说到最近的10到我当前的位置?
I have an iPhone app with a Core Data database containing a list of locations, each with lat/long coordinates. How can I search for say the nearest 10 to my current location?
我是Core Data的新用户,所以我的问题是如何做查找,我知道如何获取我当前的位置等等。我相信我需要设置一个查询词NSPredicate,但不知道应该如何写。
I'm new to Core Data so my question is really how to do the lookup, I know how to get my current location etc. I believe I need to setup an NSPredicate with a query term but not sure exactly how that should be written.
谢谢,
J
Thanks,J
推荐答案
您可以尝试此操作()
double M_PI = 3.141592653589793;
#define d2r (M_PI / 180.0)
double haversine_km(double lat1, double long1, double lat2, double long2) {
double dlong = (long2 - long1) * d2r;
double dlat = (lat2 - lat1) * d2r;
double a = pow(sin(dlat/2.0), 2) + cos(lat1*d2r) * cos(lat2*d2r) * pow(sin(dlong/2.0), 2);
double c = 2 * atan2(sqrt(a), sqrt(1-a));
double distance = 6367 * c;
return distance;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
/*Calculate distance of all locations in DB and current location. If diff. between any stop is less than x meters, perform desired operation*/
NSArray *listLocationsFromDB = [self getLocations]; //Get all locations from DB
for (Location *location in listLocationsFromDB) {
double distance = haversine_km(newLocation.coordinate.latitude, newLocation.coordinate.longitude, [location.latitude doubleValue], [location.longitude doubleValue]);
distance *= 1000;
if (distance <= 200) { //200 meters
//Your code here
}
}
}
这篇关于使用Core Data查找距离lat / long最近的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!