2015-09-24 55 views
2

,這是我的代碼,我想從10米的範圍我的當前位置最近的位置,我想與人響應的細節添加所有最近的位置還加入array.thanks如何從iOS中的陣列位置找到距離5米到10米範圍內最近的位置?

,這是我的從服務器的響應

{ 
    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); 
} 
+0

用這個代碼你的數組總是隻包含一個元素。你應該首先解析你的「回覆」 – Igor

+0

是的,我已經通過方法[self getdata]傳遞了我的迴應; –

+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); 
+0

我越來越空結果是在10個METTER位置(),陣列爲空 –

+0

,我也想他們的名字, userid和profilepic,正如我在上面的回答中提到的那樣。 –

+0

我測試了這段代碼,檢查你是否有正確的currentUserLocation。 「我也想要他們的名字」這是概念如何獲得你需要的位置,寫入額外的代碼來獲得你需要的一切 – Igor

相關問題