ある半径内のすべての場所を見つけたい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 で指定した座標は、現在の場所に近いです。