我正在开发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中提供的坐标接近我当前的位置。
最佳答案
您在代码中尝试执行的操作是地理编码,这是将坐标转换为地址的过程,而不是您想要执行的操作。相反,您需要更基本的坐标范围。您可以在上面的代码中使用distanceFromLocation:
方法,仅遍历坐标,将其转换为CLLocation
对象(如果尚未存在),然后检查到中心点的距离。
而不是使用indexesOfObjectsPassingTest
,我可能会使用filteredArrayUsingPredicate
和使用predicateWithBlock
创建的谓词来进行距离检查(除非出于某些原因实际上需要索引)。
NSArray *testLocations = @[ [[CLLocation alloc] initWithLatitude:11.2233 longitude:13.2244], ... ];
CLLocationDistance maxRadius = 30; // in meters
CLLocation *targetLocation = [[CLLocation alloc] initWithLatitude:51.5028 longitude:0.0031];
NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(CLLocation *testLocation, NSDictionary *bindings) {
return ([testLocation distanceFromLocation:targetLocation] <= maxRadius);
}];
NSArray *closeLocations = [testLocations filteredArrayUsingPredicate:predicate];
关于iphone - 获取半径内的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17548857/