2016-11-03 1 views
0

私は1つの場所から複数の場所の距離を表示する必要があるプロジェクトに取り組んでいます。場所は緯度と経度に基づいています。私は2つの場所の間の距離を取得するには、次のコードをされて使用してい複数の場所の距離を1つの場所から取得する方法と、その配列をiOSで最も近い距離で並べ替える方法はありますか?

CLLocation *locationA = [[CLLocation alloc] initWithLatitude:28.6379 longitude: 77.2432];CLLocation *locationB = [[CLLocation alloc] initWithLatitude:28.6562 longitude:77.2410];CLLocationDistance distance = [locationA distanceFromLocation:locationB];NSLog(@"Distance is %f",distance);float i = distance/1000;NSLog(@"distance between two places is %f KM", i); 

ほぼ同じ距離を示しているが、今、私は私の場所から複数の場所の距離を取得するために、構造体午前:locationA。私は

NSArray * latitudeArray = [[NSArray alloc]initWithObjects:@"28.6129",@"28.6020",@"28.5244", nil];NSArray * longitudeArray = [[NSArray alloc]initWithObjects:@"77.2295",@"77.2478",@"77.1855", nil]; 

として緯度と経度のためにNSArrayを取る例えば

..私はそれを解決するために助けてください

ソートするために私を助けてください...一つの場所としてlocationAを取ります最寄りの距離で配列します。

答えて

2

まず、緯度と経度の配列を2つ作成しないでください。これはCLLocationsの1つの配列にする必要があります。

NSMutableArray locationsArray = [[NSMutableArray alloc] init]; 
    //This is just for example, You should add locations to this array according to format of data you have available. 

    [locationsArray addObject:[[CLLocation alloc] initWithLatitude:28.6379 longitude:77.2432]]; 
    [locationsArray addObject:[[CLLocation alloc] initWithLatitude:28.6020 longitude:77.2478]]; 
    [locationsArray addObject:[[CLLocation alloc] initWithLatitude:28.5244 longitude:77.1855]]; 

は今、

CLLocation *yourLocationA ; //set whatever value you have.. 

は、次の場所での配列をソートすることができ、いくつかの基準位置を取ります。

[locationsArray sortUsingComparator:^NSComparisonResult(CLLocation *obj1Location,CLLocation *obj2Location) { 
      CLLocationDistance obj1Distance = [obj1Location distanceFromLocation: yourLocationA]; 
      CLLocationDistance obj2Distance = [obj2Location distanceFromLocation: yourLocationA]; 

      return (obj1Distance > obj2Distance); 

    }]; 
+0

回答ありがとうございます@ iOS_developer –

関連する問題