我正在開發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
陣列它顯示空(空)值。我在testLocations中提供的座標接近我的當前位置。
你的位置(座標)的列表,你想找到它們的另一個一定距離內的協調?你不需要爲此進行地理編碼。什麼是您的源數據? – Wain
我有我的數據庫中的所有位置的經度和緯度。我想找出哪些緯度和長度接近我目前的「緯度」和「經度」。 – Krunal
我的代碼有什麼問題?這將是我的'地標數組'應該conatin所有的位置名稱? – Krunal