Skip to content

Instantly share code, notes, and snippets.

@kos9kus
Last active June 28, 2016 21:57
Show Gist options
  • Save kos9kus/6e59712a7ec905df90b8a192a6db8ec2 to your computer and use it in GitHub Desktop.
Save kos9kus/6e59712a7ec905df90b8a192a6db8ec2 to your computer and use it in GitHub Desktop.
Create a predicate for LCLocation to determine a distance with specific radius
KKPosition KKPositionMake(double latitude, double longitude, double r) {
KKPosition p;
p.latitude = latitude;
p.longitude = longitude;
p.radius = r;
return p;
}
#define deg2rad(degrees) ((M_PI * degrees)/180)
NSPredicate* createPredicateWIthRadius(KKPosition position) {
float minLat = position.latitude - (position.radius / 69);
float maxLat = position.latitude + (position.radius / 69);
float minLon = position.latitude - position.radius / fabs(cos(deg2rad(position.latitude))*69);
float maxLon = position.longitude + position.radius / fabs(cos(deg2rad(position.latitude))*69);
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"latitude <= %f AND latitude >= %f AND longitude <= %f AND longitude >= %f", maxLat, minLat, maxLon, minLon];
return predicate;
}
NSPredicate* createPredicateWIthRadius_2(KKPosition position) {
double const D = position.radius;
double const R = 6371009.; // Earth readius in meters
double meanLatitidue = position.latitude * M_PI / 180.;
double deltaLatitude = D / R * 180. / M_PI;
double deltaLongitude = D / (R * cos(meanLatitidue)) * 180. / M_PI;
double minLatitude = position.latitude - deltaLatitude;
double maxLatitude = position.latitude + deltaLatitude;
double minLongitude = position.longitude - deltaLongitude;
double maxLongitude = position.longitude + deltaLongitude;
NSPredicate *predicate = [NSPredicate predicateWithFormat:
@"(%@ <= longitude) AND (longitude <= %@)"
@"AND (%@ <= latitude) AND (latitude <= %@)",
@(minLongitude), @(maxLongitude), @(minLatitude), @(maxLatitude)];
return predicate;
}
// Another case
CLLocation *targetPoint = [[CLLocation alloc] initWithLatitude:position.latitude longitude:position.longitude];
NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(Item * _Nonnull object, NSDictionary<NSString *,id> * _Nullable bindings) {
CLLocation *locationObj = [[CLLocation alloc] initWithLatitude:[object.latitude doubleValue] longitude:[object.longitude doubleValue]];
BOOL resultBool = partnerName != nil ? ( [locationObj distanceFromLocation:targetPoint] <= position.radius ) && ( [object.partnerName isEqualToString:partnerName] ) : ( [locationObj distanceFromLocation:targetPoint] <= position.radius ) ;
return resultBool;
}];
typedef struct {
double longitude;
double latitude;
int radius;
} KKPosition;
KKPosition KKPositionMake(double lng, double ltd, double r);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment