用位置距离计算最大和最小经纬度 – 目标C
我需要从一定距离的位置计算MAX和MIN纬度和经度值。
我有成千上万个存储在CoreData中的位置,我只想显示距离用户位置5公里内的位置。
我怎样才能解决这个问题?
这是一个可能的解决scheme:
-
macros将Degrees转换为Radians
#define deg2rad(degrees) ((degrees) / 180.0 M_PI)
-
macros来保持我的search距离
#define searchDistance 5.00 //float value in KM
-
设置纬度,经度的最小值和最大值
float minLat = userLocation.coordinate.latitude - (searchDistance / 69); float maxLat = userLocation.coordinate.latitude + (searchDistance / 69); float minLon = userLocation.coordinate.latitude - searchDistance / fabs(cos(deg2rad(userLocation.coordinate.latitude))*69); float maxLon = userLocation.coordinate.longitude + searchDistance / fabs(cos(deg2rad(userLocation.coordinate.latitude))*69);
-
创build谓词如下
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"latitude <= %f AND latitude >= %f AND longitude <= %f AND longitude >= %f", maxLat, minLat, maxLon, minLon];
这将在userLocation
周围创build一个正方形,并检查给定的位置是否落入其坐标。
更新:Swift 2. *实现
首先创build一个函数来计算度数为弧度
func deg2rad(degrees:Double) -> Double{ return degrees * M_PI / 180 }
计算并创build最小和最大Latitude
和Longitude
值
let searchDistance:Double = 5.00 //float value in KM let minLat = userLocation.coordinate.latitude - (searchDistance / 69) let maxLat = userLocation.coordinate.latitude + (searchDistance / 69) let minLon = userLocation.coordinate.longitude - searchDistance / fabs(cos(deg2rad(userLocation.coordinate.latitude))*69) let maxLon = userLocation.coordinate.longitude + searchDistance / fabs(cos(deg2rad(userLocation.coordinate.latitude))*69)
最后创buildNSPredicate
以查询CoreData
的位置。 在我的情况下,我正在查询值的latitude
和longitude
但你应该改变这个来匹配你的CoreData
对象
let predicate = NSPredicate(format: "latitude <= \(maxLat) AND latitude >= \(minLat) AND longitude <= \(maxLon) AND longitude >= \(minLon)")
使用CoreLocation方法distanceFromLocation:
它返回两点之间的距离(以米为单位)
CLLocation* location = [[CLLocation alloc] initWithLatitude:lat longitude:lon]; if([userLocation distanceFromLocation:location) < searchDistance) // do something with close point
一个合适的谓词可以被构造为:
NSPredicate* predicate = [NSPredicate predicateWithBlock:(BOOL (^)(NSDictionary* target, NSDictionary *bindings)) { CLLocation* location = [[CLLocation alloc] initWithLatitude:[target[@"lat"] doubleValue] longitude:[target[@"lon"] doubleValue]]; return [userLocation distanceFromLocation:location] < searchDistance; }];
这有一个好处,它返回实际在范围内的项目,而不是在一个正方形范围内的项目。 这也是(可能,我们不知道细节)使用更精确的范围本身的近似值。 它的缺点是谓词需要加载每个对象,因为它不能被表示为一个sqlite查询。