Calculating MAX and MIN Latitude and Longitude with distance from Location - Objective C

后端 未结 2 546
挽巷
挽巷 2021-01-12 15:17

I need to compute MAX and MIN Latitude and Longitude values from a location with certain distance.

I have thousands of locations stored in CoreData, and I want to sh

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-12 15:36

    Use the CoreLocation method distanceFromLocation: which returns the distance (in meters) between two points as such:

    CLLocation* location = [[CLLocation alloc] initWithLatitude:lat longitude:lon];
    if([userLocation distanceFromLocation:location) < searchDistance)
        // do something with close point
    

    A suitable predicate can be constructed as:

    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;
    }];
    

    This has the advantage that it returns the items actually within range, as opposed to the items in a square approximating the range. It's also (probably, we don't know the details) using a more accurate approximation of the range itself. It has the disadvantage that the predicate requires loading every object since it can't be expressed as an sqlite query.

提交回复
热议问题