如何在iOS中从一系列位置找到5米到10米之间的最近位置?

时间:2015-09-24 10:22:30

标签: ios objective-c iphone

这是我的代码,我希望距离我当前位置最近的位置在10米的范围内,我想要添加所有最近的位置以及响应的人的详细信息也添加到array.thanks

这是我对服务器的回应

{
    born = 0;
    completed = 0;
    "emergency_id" = "-1";
    eyes = "";
    feet = 0;
    "first_name" = Neil;
    glasses = No;
    hair = "";
    inch = 0;
    language = "<null>";
    "last_name" = Ferris;
    latitude = "30.1456987";
    longitude = "76.69916";
    marks = "";
    "member_id" = 21634;
    picture = "";
    "profile_id" = 5826;
    type = 1;
    updated = "2015-09-16 06:32:08";
    weight = 0;
}        

如上所述我从服务器获得5000个用户,在通过我当前位置10米距离过滤后,我需要在表格视图中显示10米范围以内的列表

- (void)getdata
{
    NSString * apiURLStr =[NSString stringWithFormat:@"<MY API URL>"];

    NSString *outputStr = [NSString stringWithContentsOfURL:[NSURL URLWithString:apiURLStr] encoding:NSUTF8StringEncoding error:nil];
    NSDictionary *response;
    if (outputStr == nil)
    {
        return;

    }

    NSData* data = [outputStr dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;
    response = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

    NSMutableArray *array=[[NSMutableArray alloc]init];
    CLLocation *closestLocation = nil;
    for (NSDictionary *dict in response)
    {
        NSString *latitude=[dict valueForKey:@"latitude"];
        NSString *longitude=[dict valueForKey:@"longitude"];

        CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude.doubleValue
        longitude:longitude.doubleValue];

        [array addObject:location];
    }

    CLLocationDistance closestLocationDistance = DBL_MIN;

    for (CLLocation *location in array)
    {
        if (!closestLocation) {
            closestLocation = location;
            closestLocationDistance = [currentUserLocation distanceFromLocation:location];
            continue;
        }
        CLLocationDistance currentDistance = [currentUserLocation distanceFromLocation:location];
        if (currentDistance < closestLocationDistance)
        {
            closestLocation = location;
            closestLocationDistance = currentDistance;
        }
    }

    NSLog(@"closestLocation %@",closestLocation.description);
    NSLog(@"closestLocationDistance %f", closestLocationDistance);
}

1 个答案:

答案 0 :(得分:2)

  

感谢答案兄弟,但我想要在10米范围内的最近位置列表。

NSMutableArray *locationsInRange = [NSMutableArray new];

for (CLLocation *location in array)
{
    CLLocationDistance currentDistance = [currentUserLocation distanceFromLocation:location];
    if (currentDistance < 10)
    {
        [locationsInRange addObject:location];
    }
}

NSLog(@"locations in 10 metters %@",locationsInRange.description);