I am working on a project in which I have to show the distance of multiple locations from one location. locations are based on latitude and longitude.
I am using the following code to get the distance between two locations is shows nearly same distance
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);
but now i am struct to get the distance of multiple locations from my location: locationA.
for example I take NSArray for latitude and longitude as
NSArray * latitudeArray = [[NSArray alloc]initWithObjects:@"28.6129",@"28.6020",@"28.5244", nil];NSArray * longitudeArray = [[NSArray alloc]initWithObjects:@"77.2295",@"77.2478",@"77.1855", nil];
Please help me to resolve it..
Take locationA as one location..
Please help me to sort the Array by nearest Distance..
First of all, don't create two array for latitude and longitude, It should be one array of CLLocations.
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]];
Now, Take some reference location,
CLLocation *yourLocationA ; //set whatever value you have..
You can sort array of location with following.
[locationsArray sortUsingComparator:^NSComparisonResult(CLLocation *obj1Location,CLLocation *obj2Location) {
CLLocationDistance obj1Distance = [obj1Location distanceFromLocation: yourLocationA];
CLLocationDistance obj2Distance = [obj2Location distanceFromLocation: yourLocationA];
return (obj1Distance > obj2Distance);
}];
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments