我正在开发 iOS 应用程序,我想在其中找到某个半径内的所有位置。
在objective-c中有什么方法可以让我指定一个固定的半径和一个位置,这会告诉我哪些位置在那个半径内?
我做了一些研究,我得到了这个代码片段,
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:locationManager.location
completionHandler:^(NSArray *placemarks, NSError *error)
{
NSLog(@"reverseGeocodeLocation:completionHandler: Completion Handler called!");
if (error)
{
NSLog(@"Geocode failed with error: %@", error);
return;
}
CLLocationDistance radius = 30;
CLLocation* target = [[CLLocation alloc] initWithLatitude:51.5028 longitude:0.0031];
NSArray *locationsWithinRadius = [placemarks objectsAtIndexes:
[placemarks indexesOfObjectsPassingTest:
^BOOL(id obj, NSUInteger idx, BOOL *stop) {
return [(CLLocation*)obj distanceFromLocation:target] < radius;
}]];
NSLog(@"locationsWithinRadius=%@",locationsWithinRadius);
}];
但它会崩溃并显示错误:
由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[CLPlacemark distanceFromLocation:]:
我走对了吗?这是一种从我指定的位置查找所有位置的方法吗?
提前致谢。
编辑:
NSArray *testLocations = @[[[CLLocation alloc] initWithLatitude:19.0759 longitude:72.8776]];
CLLocationDistance maxRadius = 3000; // in meters
CLLocation *targetLocation = [[CLLocation alloc] initWithLatitude:newLocation.coordinate.latitude longitude:newLocation.coordinate.longitude]; //Current location coordinate..
NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(CLLocation *testLocation, NSDictionary *bindings) {
return ([testLocation distanceFromLocation:targetLocation] <= maxRadius);
}];
NSArray *closeLocations = [testLocations filteredArrayUsingPredicate:predicate];
NSLog(@"closeLocations=%@",closeLocations);
当我记录我的closeLocations
数组时,它显示 null(Empty) 值。我在 testLocations 中提供的坐标靠近我当前的位置。