How to add elements to an array created by a 'for' loop ? - iphone

I am using for loop for get distance from current location to destination location. I would like an array that contains all distances from current to destination location.
for (i = 0; i < [Arr_Lat count]; i++)
{
NSString *latst1 = [[NSString alloc]initWithFormat:[Arr_Lat objectAtIndex:i]];
NSString *longst1 = [[NSString alloc]initWithFormat:[Arr_Long objectAtIndex:i]];
NSLog(#"First lat : %#",latst1);
NSLog(#"First ong : %#",longst1);
double Doblat1 = [latst1 doubleValue];
double Doblong1 = [longst1 doubleValue];
CLLocationCoordinate2D coord1 = CLLocationCoordinate2DMake(coord1.latitude = Doblat1, coord1.longitude = Doblat1);
NSLog(#" Coordinat ==== : %f -- %f",coord1.latitude,coord1.longitude) ;
CLLocation *currLoc = [[CLLocation alloc] initWithLatitude:appDel.curr_lat longitude:appDel.curr_long];
CLLocation *destLoc1 = [[CLLocation alloc] initWithLatitude:Doblat1 longitude:Doblong1];
NSLog(#" Currennt Location : %#", currLoc);
NSLog(#" Destination Location : %#" , destLoc1);
distance = [destLoc1 distanceFromLocation:currLoc];
NSLog(#" Distance : ------- %0.3f", distance);
DistStr = [[NSString alloc]initWithFormat:#" %f",distance];
[currLoc release];
[destLoc1 release];
[Arr_title retain];
[tbl_nearplace reloadData];
}

If you want to store the distance you need an NSMutableArray.
Declare a NSMutableArray *distanceArray; in class scope.
Initialize it: distanceArray = [[NSMutableArray alloc] init];
In the for loop after DistStr =[[NSString alloc]initWithFormat:#" %f",distance];
write the following code:
[distanceArray addObject:DistStr];

Say we have this array with stuff we want to iterate over and add those items to another array
NSArray *someArrayWithStuff = #[#"Hello",
#"Its",
#"Very",
#"Cold",
#"Outside",
#"Today"];
Say we want the content of someArrayWithStuff to be added to this other array so we create an NSMutableArray
NSMutableArray *theNewArrayWithOurStuff = [NSMutableArray array];
We loop through the someArrayWithStuff
for (int i = 0; i < someArrayWithStuff.count; i++) {
// Add object to the new array
[theNewArrayWithOurStuff addObject:[someArrayWithStuff objectAtIndex:i]];
}

NSMutableArray *Distance=[[NSMutableArray alloc]Init];
for (i = 0; i < [Arr_Lat count]; i++)
{
NSString *latst1 = [[NSString alloc]initWithFormat:[Arr_Lat objectAtIndex:i]];
NSString *longst1 = [[NSString alloc]initWithFormat:[Arr_Long objectAtIndex:i]];
NSLog(#"First lat : %#",latst1);
NSLog(#"First ong : %#",longst1);
double Doblat1 = [latst1 doubleValue];
double Doblong1 = [longst1 doubleValue];
CLLocationCoordinate2D coord1 = CLLocationCoordinate2DMake(coord1.latitude = Doblat1, coord1.longitude = Doblat1);
NSLog(#" Coordinat ==== : %f -- %f",coord1.latitude,coord1.longitude) ;
CLLocation *currLoc = [[CLLocation alloc] initWithLatitude:appDel.curr_lat longitude:appDel.curr_long];
CLLocation *destLoc1 = [[CLLocation alloc] initWithLatitude:Doblat1 longitude:Doblong1];
NSLog(#" Currennt Location : %#", currLoc);
NSLog(#" Destination Location : %#" , destLoc1);
distance = [destLoc1 distanceFromLocation:currLoc];
NSLog(#" Distance : ------- %0.3f", distance);
NSString *DistStr = [[NSString alloc]initWithFormat:#" %f",distance];
[Distance addObject:DistStr];
[DistStr release];
[currLoc release];
[destLoc1 release];
[Arr_title retain];
[tbl_nearplace reloadData];
}

Related

iPhone distance from current location as subtitle

I am trying to find distance from selectedAnnotation to userLocation. I added the following code in the annotation NSObject:
-(void) setDistanceFromCurrentLocation:(CLLocation *)currentLocation{
CLLocation *location2 = [[CLLocation alloc] initWithLatitude:self.latitude longitude:self.longitude];
[self setDistance:[currentLocation distanceFromLocation:location2]];
}
- (NSString *)subtitle
{
NSString *myDistance = [NSString stringWithFormat:#"%1.1f from current location", distance];
return myDistance;
}
Now in the didUpdatedidUpdateToLocation I tried using the following logic from this question: https://stackoverflow.com/a/10881683/984248
Still getting 0.0 back. What am I doing wrong?
EDIT:
So I am calculating the distance from current location correctly now. But how do I pass this on to set it as the subtitle to a pin?
Here is how I am finding distance:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
[self setCurrentLocation:newLocation];
// if not Current Location then update the currently displayed Dealer Annotation
for (int i=0; i<self.dataArray.count; i++){
NSDictionary *dataDictionary = [self.dataArray objectAtIndex:i];
NSArray *array = [dataDictionary objectForKey:#"Locations"];
for (int i=0; i<array.count; i++){
NSMutableDictionary *dictionary = [array objectAtIndex:i];
CLLocation *pinLocation = [[CLLocation alloc] initWithLatitude:[[dictionary objectForKey:#"Latitude"] doubleValue] longitude:[[dictionary objectForKey:#"Longitude"] doubleValue]];
[?????? setDistance:[self.currentLocation distanceFromLocation:pinLocation]];
}
}
}
Here is how I am adding pins to the map:
for (int i=0; i<self.dataArray.count; i++){
NSDictionary *dataDictionary = [self.dataArray objectAtIndex:i];
NSArray *array = [dataDictionary objectForKey:#"Locations"];
for (int i=0; i<array.count; i++){
NSMutableDictionary *dictionary = [array objectAtIndex:i];
MapAnnotation *annotation = [[MapAnnotation alloc] init];
annotation.latitude = [[dictionary objectForKey:#"Latitude"] doubleValue];
annotation.longitude = [[dictionary objectForKey:#"Longitude"] doubleValue];
CLLocationCoordinate2D coord = {.latitude =
annotation.latitude, .longitude = annotation.longitude};
MKCoordinateRegion region = {coord};
annotation.title = [dictionary objectForKey:#"Name"];
annotation.subtitle = ?????;
annotation.coordinate = region.center;
//Saving the dictionary of the pin to show contact info later
annotation.sourceDictionary = dictionary;
[mapView addAnnotation:annotation];
}
}
Just wondering, is currentLocation set to self.latitude,self.longitude?
in which case you would be trying to find the distance from yourself. Try logging the latitude and longitude values of the currentLocation parameter and the self.latitude and self.longitude variables, and make sure they are different.
If they are, then try logging [currentLocation distanceFromLocation:location2] to see if it is non zero, if it is, then your setDistance method is the problem.
Other than that all I can think of is your distance variable is getting set to 0 somewhere else, or it is a variable that does not format with %1.1f so the formatter is setting it to 0.0

iPhone: Sorting based on location

I have been working on an iPhone app, where-in i have list of users in a NSMutableArray like below.
myMutableArray: (
{
FirstName = Getsy;
LastName = marie;
Latitude = "30.237314";
Longitude = "-92.461008";
},
{
FirstName = Angel;
LastName = openza;
Latitude = "30.260329";
Longitude = "-92.450414";
},
{
FirstName = Sara;
LastName = Hetzel;
Latitude = "30.2584499";
Longitude = "-92.4135357";
}
)
I need to sort users based on the location who is nearby to my location by calculating latitude and longitude. I am not able to achieve this till now. Could someone help me on giving some samples?
UPDATED: I am trying like below as per Mr.sch suggested. Please check my updated code. Is it fine?.
NSArray *orderedUsers = [myMutableArray sortedArrayUsingComparator:^(id a,id b) {
NSArray *userA = (NSArray *)a;
NSArray *userB = (NSArray *)b;
CGFloat aLatitude = [[userA valueForKey:#"Latitude"] floatValue];
CGFloat aLongitude = [[userA valueForKey:#"Longitude"] floatValue];
CLLocation *participantALocation = [[CLLocation alloc] initWithLatitude:aLatitude longitude:aLongitude];
CGFloat bLatitude = [[userA valueForKey:#"Latitude"] floatValue];
CGFloat bLongitude = [[userA valueForKey:#"Longitude"] floatValue];
CLLocation *participantBLocation = [[CLLocation alloc] initWithLatitude:bLatitude longitude:bLongitude];
CLLocation *myLocation = [[CLLocation alloc] initWithLatitude:locationCoordinates.latitude longitude:locationCoordinates.longitude];
CLLocationDistance distanceA = [participantALocation distanceFromLocation:myLocation];
CLLocationDistance distanceB = [participantBLocation distanceFromLocation:myLocation];
if (distanceA < distanceB) {
return NSOrderedAscending;
} else if (distanceA > distanceB) {
return NSOrderedDescending;
} else {
return NSOrderedSame;
}
}];
Thank you!
NSArray *orderedUsers = [users sortedArrayUsingComparator:^(id a,id b) {
User *userA = (User *)a;
User *userB = (User *)b;
CLLocationDistance distanceA = [userA.location getDistanceFromLocation:myLocation];
CLLocationDistance distanceB = [userB.location getDistanceFromLocation:myLocation];
if (distanceA < distanceB) {
return NSOrderedAscending
} else if (distanceA > distanceB) {
return NSOrderedDescending;
} else {
return NSOrderedSame;
}
}];
First thing, you will need to calculate the distance between your current location and the location of each other user.
Talking mathematically, here is a Wolfram|Alpha example
Now "programmatic-ally", you can use CLLocation class, here is an example:
(CLLocationDistance)getDistanceFrom:(const CLLocation *)location
But first you will need to create the location object from your Latitude and Longitude. You can use:
(id)initWithLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude
You can calculate the distance (geographical, not flat plane!) between your position and each of these items' positions and order by that value.
- (void)viewDidLoad {
[super viewDidLoad];
// This Array Taken Globally
List_of_locationsArray =[[NSMutableArray alloc]initWithObjects:
#{#"latitude" : #"17.415045",#"logitude":#"78.421424"} ,#{#"latitude" : #"17.415045",#"logitude":#"78.421424"},#{#"latitude" : #"17.415045",#"logitude":#"78.421424"},#{#"latitude" : #"17.415045",#"logitude":#"78.421424"},#{#"latitude" : #"17.415045",#"logitude":#"78.421424"}
,nil];
}
-(void)sortingLocationsArray{
// CLLocation* currentLocation =[[CLLocation alloc]initWithLatitude:[currentLatitude doubleValue] longitude:[currentLogitude doubleValue]];
CLLocation* currentLocation =[[CLLocation alloc]initWithLatitude: currentLatitudeHere longitude:CurrentLogHere];
NSMutableArray* tempLocationsArr = [[NSMutableArray alloc]initWithCapacity:[locationsArray count]];
for (int i=0; i<[locationsArray count]; i++) {
CLLocationDegrees latValue = [[locationsArray[i] objectForKey:#"latitude"] doubleValue];
CLLocationDegrees longValue = [[locationsArray[i] objectForKey:#"logitude"] doubleValue];
CLLocation* location = [[CLLocation alloc]initWithLatitude:latValue longitude:longValue];
[tempLocationsArr addObject:location];
NSArray* sortLocationArry = [tempLocationsArr sortedArrayUsingComparator:^NSComparisonResult(CLLocation* location1, CLLocation* location2) {
CLLocationDistance distA = [location1 distanceFromLocation:currentLocation];
CLLocationDistance distB = [location2 distanceFromLocation:currentLocation];
if (distA < distB) {
return NSOrderedAscending;
} else if ( distA > distB) {
return NSOrderedDescending;
} else {
return NSOrderedSame;
}
}];
//ArrayAfterSorting is another mutable Array to Store Sorting Data
[ArrayAfterSorting removeAllObjects];
[sortLocationArry enumerateObjectsUsingBlock:^(CLLocation* location, NSUInteger idx, BOOL *stop) {
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc]init];
[tempDict setObject:[NSString stringWithFormat:#"%f",location.coordinate.latitude] forKey:#"latitude"];
[tempDict setObject:[NSString stringWithFormat:#"%f",location.coordinate.longitude] forKey:#"logitude"];
[ArrayAfterSorting addObject:tempDict];
}];
NSLog(#"sortedArray : %#", ArrayAfterSorting);
}
}
You may solve your problem in following way
1)Firstly store all above values in separate array Like latArray ,longArray,nameArray
2)Now get the distance between location(longArray,latArray) from your current location.
Then store these distances in separate Array(distanceArray).
//getDistance Between currentLocation and desired Location
-(void *)getDistanceFromCurrentLocation{
for(int val=0;val<[latArray count];val++){
NSString *dis_From_Current_Location;
dis_From_Current_Location =nil;
CGFloat str_Longitude=[[defaults objectForKey:#"long"]floatValue];
CGFloat str_Latitude=[[defaults objectForKey:#"lati"]floatValue];
//Suppose this is your current location
CGFloat lat1= [[latArray objectAtIndex:val]floatValue];
//these array for lat
CGFloat long1=[[longArray objectAtIndex:val]floatValue];
//these array for longArray
CLLocation *location1 = [[CLLocation alloc] initWithLatitude:lat1 longitude:long1];
CLLocation *location2 = [[CLLocation alloc] initWithLatitude:str_Latitude longitude:str_Longitude];
CLLocationDistance dist=[location1 distanceFromLocation:location2];
NSLog(#"Distance i meters: %f", [location1 distanceFromLocation:location2]);
long long v = llabs(dist/1000);
dis_From_Current_Location=[NSString stringWithFormat:#"%lld km",v];
[location1 release];
[location2 release];
[distanceArray addObject: dis_From_Current_Location];
//distanceArray is Global NsMutableArray.
}
}
Now You should Apply sorting method(selection, bubble) fro sorting the distances.
One thing need to care is that when you sort the distanceArray
please adjust values of nameArray as according to the distanceArray
See Below code for sorting the distanceArray and adjust the nameArray's value.
-(void)getSoretdArray{
NSString * tempStr,*tempStr2;
for(int i=0;i<[distanceArray count]; i++){
for(int j=i+1;j<[distanceArray count]; j++){
if([distanceArray objectAtIndex:j]>[distanceArray objectAtIndex:j+1]){
tempStr=[distanceArray objectAtIndex:j];
NSString* str= [distanceArray objectAtIndex:j+1];
[ distanceArray insertObject:str atIndex:j];
[distanceArray insertObject:tempStr atIndex:j+1] ;
//also change the name of corresponding location.
//you have to adjust the stored names in namArray for storing names of Corresponding Distances
tempStr2=[nameArray objectAtIndex:j];
NSString* str1= [nameArray objectAtIndex:j+1];
[ nameArray insertObject:str1 atIndex:j];
[nameArray insertObject:tempStr2 atIndex:j+1] ;
}
}
}
}
This will definitely work just try to use carefully

how to create an C Array

his guys,
i think this is a simple question but i do not know how to do it.
how do i create the line below dynamically from an array?
this is what i need to call.
//data source
NSString * sourceData[7] = {#"2", #"1", #"4", #"8", #"14", #"15", #"10"};
chartData = [WSData dataWithValues:[WSData arrayWithString:sourceData withLen:7]];
+ (NSArray *)arrayWithString:(NSString *[])strings
withLen:(NSUInteger)len {
NSMutableArray *tmpArr = [NSMutableArray
arrayWithCapacity:len];
NSUInteger i;
for (i=0; i<len; i++) {
[tmpArr addObject:strings[i]];
}
return [NSArray arrayWithArray:tmpArr];
}
thanks for all the help especially Daniel :)
this is the answer to the question
NSMutableArray * dayArray = [[NSMutableArray alloc] init];
dayArray = [NSMutableArray arrayWithCapacity:7];
NSMutableArray * sdArray = [[NSMutableArray alloc] init];
sdArray = [NSMutableArray arrayWithCapacity:7];
NSInteger drunked = [appDelegate.drinksOnDayArray count];
if (drunked !=0)
{
for(int i=6; i>=0; i--)
{
DayOfDrinks *drinksOnDay = [appDelegate.drinksOnDayArray objectAtIndex:i];
NSString * dayString= [NSDate stringForDisplayFromDateForChart:drinksOnDay.dateConsumed];
[dayArray addObject:dayString];//X label for graph the day of drink.
drinksOnDay.isDetailViewHydrated = NO;
[drinksOnDay hydrateDetailViewData];
NSNumber *sdNumber = drinksOnDay.standardDrinks;
[sdArray addObject: sdNumber];
}
NSString *sData[7];// = malloc(7 * sizeof(NSString *));
for (int i=0; i<7; i++)
{
DayOfDrinks *drinksOnDay = [appDelegate.drinksOnDayArray objectAtIndex:i];
sData[i] = [NSString stringWithFormat:#"%#",drinksOnDay.standardDrinks];
}
NSString * sourceData[7] = {sData[6],sData[5],sData[4],sData[3],sData[2],sData[1],sData[0] };
}
If you are only using the array as a call parm, and are not storing it somewhere or returning it from your current method:
NSString* sourceData[7];
for (i = 0; i < 7; i++) {
int num = <getTheValueYouWant>;
sourceData[i] = [NSString stringWithFormat:#"%d", num];
}
But note that if you intend to return the array, or store it in some long-lived variable, you need an entirely different setup.
So this is how you would create an NSMutableArray. Mutable because you're creating it at runtime.
NSString * sourceData = [[NSString alloc] initWithFormat:#""];
//assuming the array you have is arr with NSNumber objects
for (NSNumber *num in arr) {
[sourceData stringByAppendingFormat:#"%#", num];
}
You can try below code with the loop as you required.....
NSMutableArray *array;
array = [[NSMutableArray alloc] init];
[array addObject:[NSNumber numberWithFloat:1.0f]];
[array release];

distance from CurrentLocation to data from Plist File

I have a long list of places with Latitudes and Longitudes in a plist. I want to show a tableView of the places only within X distance of the user's current location. Is there a way to create objects from the lats & longs in the plist file so I can use 'distanceFromLocation'? More importantly, how do I get the array to only display the names with a distance from current less than X? I'm assuming I would need to make a series of objects from lats & longs in the plist, then do an objects in array if objects distanceFrom is less than X, correct?
Please help.
Here's where I am now: I get an error on the double clubLatitude line
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *clubArray = [NSArray arrayWithObjects:[self danceClubLocation], nil];
self.tableData = clubArray;
}
-(CLLocation *)danceClubLocation
{
NSString *plistPath = [[NSBundle mainBundle] pathForResource:#"Data" ofType:#"plist"];
NSArray *array = [NSArray arrayWithContentsOfFile:plistPath];
NSEnumerator *e = [array objectEnumerator];
id object;
while ((object = [e nextObject])) {
double clubLatitude = [[array valueForKey:#"Latitude"] doubleValue];
double clubLongitude = [[array valueForKey:#"Longitude"] doubleValue];
CLLocation *clubLocation = [[CLLocation alloc] initWithLatitude:clubLatitude longitude:clubLongitude];
if ([clubLocation distanceFromLocation:myLocation]<=50) {
return clubLocation;
}
else return nil;
}
return nil;
}
-(CLLocation *)myLocation
{
CLLocation *location = [locationManager location];
CLLocationCoordinate2D coordinate = [location coordinate];
NSNumber *myLatitude = [NSNumber numberWithDouble:coordinate.latitude];
NSNumber *myLongitude = [NSNumber numberWithDouble:coordinate.longitude];
double myLatitudeD = [myLatitude doubleValue];
double myLongitudeD = [myLongitude doubleValue];
myLocation = [[CLLocation alloc]initWithLatitude:myLatitudeD longitude:myLongitudeD];
return myLocation;
}
As #DavidNeiss said, you have to iterate over the list (an NSArray with the plist as source) and it would be something like this:
NSString *plistPath = [[NSBundle mainBundle] pathForResource:#"latlong" ofType:#"plist"];
NSArray *array = [NSArray arrayWithContentsOfFile:plistPath];
NSEnumerator *e = [array objectEnumerator];
id object;
while (object = [e nextObject]) {
// do something with object
}
Then you can do what you want (removing what's far from the user or whatever).
Read in your plist, iterate over it to pull out ones within X distance and populate any array with them that will be the data source for your table view?

NSString: fastes way of splitting

my question is a performance question.
I need to split a huge NSString into coordinates. The string has this format:
#"coordx,coordy coordx,coordy coordx,coordy (...)"
My method to parse this is:
-(NSMutableArray*) parsePath:(NSString*) pathString
{
// first split between the coordinates
NSArray* path = [pathString componentsSeparatedByString:#" "];
NSMutableArray* coords = [[NSMutableArray alloc] init];
static NSString *seperator = #",";
NSArray *coord;
for(NSString *coordString in path)
{
coord = [coordString componentsSeparatedByString:seperator];
Coordinate *c = [[Coordinate alloc]init];
c.x = [[coord objectAtIndex:0] intValue];
c.y = [[coord objectAtIndex:1] intValue];
[coords addObject:c];
[c release];
}
return coords;
}
So, is there any way to make this faster?
Thanks!
Sebastian
Using NSScanner is probably faster.
http://developer.apple.com/iphone/library/documentation/cocoa/reference/Foundation/Classes/NSScanner_Class/Reference/Reference.html