autoupdate a distance between two locations in objective c - iphone

I'm very new to objective-c and have tried several sources to find an answer. No luck so far. Please help me out.
I'm building an app with location functionality.
The app has to give an alert when a given distance is covered.
Therefore I have to save a initial location. When moving the actual position has to be displayed andt the distance as well.
What I did is the following:
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
//display latitude
NSString *lat =[[NSString alloc]initWithFormat:#"%f",
newLocation.coordinate.latitude];
latitude.text=lat;
//latr = lat;
//display longitude
NSString *lon = [[NSString alloc]initWithFormat:#"%f",
newLocation.coordinate.longitude];
longitude.text=lon;
//longr = lon;
//display accuracy
//NSString *acc = [[NSString alloc]initWithFormat:#"%f",
// newLocation.horizontalAccuracy];
//accuracy.text=acc;
}
-(void)recordLocation{
double valueLat = [[latitude text]doubleValue];
int latSeconds = valueLat * 3600;
int latDegrees = latSeconds / 3600;
latSeconds = abs(latSeconds % 3600);
int latMinutes = latSeconds / 60;
latSeconds %= 60;
char latChar = (latitude > 0) ? 'N' : 'S';
double valueLon = [[longitude text]doubleValue];
int lonSeconds = valueLon * 3600;
int lonDegrees = lonSeconds / 3600;
lonSeconds = abs(lonSeconds % 3600);
int lonMinutes = lonSeconds / 60;
lonSeconds %= 60;
char lonChar = (longitude > 0) ? 'E' : 'W';
CLLocation *tempPos = [[CLLocation alloc] initWithLatitude:valueLat longitude:valueLon];
NSString *recPosition = [[NSString alloc]initWithFormat:#"%i° %i' %i\" %c" " " #"%i° %i' %i\" %c \n", latDegrees, latMinutes, latSeconds, latChar,lonDegrees, lonMinutes, lonSeconds, lonChar];
_labelDegrees.text = recPosition;
NSLog(#"%f" , valueLat);
NSLog(#"%f" , valueLon);
NSLog (#"%#", tempPos);
[self distanceFromLocation:tempPos];
}
- (CLLocationDistance)distanceFromLocation:(const CLLocation *)tempPos{
double lat1 = [[latitude text] doubleValue];
double lon1 = [[longitude text] doubleValue];
CLLocation *currentLocation = [[CLLocation alloc] initWithLatitude:lat1 longitude:lon1];
CLLocationDistance locDistance = [currentLocation distanceFromLocation:tempPos];
NSString *distText = [[NSString alloc]initWithFormat:#"%f", locDistance];
NSLog(#"%#", currentLocation);
NSLog(#"%f", locDistance);
NSLog(#"%#", distText);
[lonDistance setText:distText];
}
It workes, but only one time, when I click a Button in my interface.There is no autoupdat of locDistance.
The initial location updates automatic (found on the internet), the recording of this position is ok as well.
What is wrong in my code. It is possible a simple issue but I'm not able to find the solution.
(Please forgive my poor English, I'm dutch)
Thank you in advance for your help
Regards,
Adri

You need to call recordLocation from within the didUpdateToLocation:fromLocation: method. That method is called automatically by the location manager whenever the location changes by more than the distanceFilter distance that can be set on the location manager. When it gets called, you want it to call recordLocation, which in turn calls distanceFromLocation.
locationManager:didUpdateToLocation:fromLocation: is depreciated in iOS 6, so if you're using that iOS, then you should be using locationManager:didUpdateLocations:

Related

Cannot get GPS location on iPhone

My app runs perfectly on the simulator and everything works fine. But now i wanted to thest it on my iPhone and i found out that the GPS funcution don't work.
Here is my code.
[super viewDidLoad];
//eigener Standort
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
eigLat = newLocation.coordinate.latitude;
eigLon = newLocation.coordinate.longitude;
eigLatString = [NSString stringWithFormat:#"%f", eigLat];
eigLonString = [NSString stringWithFormat:#"%f", eigLon];
}
And till now everything is fine. If i use NSLog i get the right coordinates.
But then i want to use my coordinates here:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
news = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:NULL];
for (x=0; x<[news count]; x++)
{
//Berechnung der Entfernung
erdradius = 6371.1;
//Koordinaten von Datenbank in String schreiben
NSString *latitude = [[news objectAtIndex:x] objectForKey:#"Latitude"];
NSString *longitude = [[news objectAtIndex:x] objectForKey:#"Longitude"];
entfernung = 0;
double lat1 = eigLat; //eigener Standort Latitude
double long1 = eigLon; //eigener Standort Longitude
double lat2 = [latitude doubleValue]; //Standort Heurigen Latitude
double long2 = [longitude doubleValue]; //Standort Heurigen Longitude
And there I get everytime 0 for lat1 and lat2. But only if I Run the App on the iPhone. On the Simulator it works fine.
Does someone know why this could be?
The problem is that you did not get yet a GPS location in real world, so
your method connectionDidFinishLoading() is called before didUpdateToLocation() was called.
Therefoe eighValue is still 0.
Check first for valid lat and longitude:
if both are 0 then you did not get a location.
I think that you must change the logic of your program code,
you have to either
1) wait till you have a location, and then start the
connection such that connectionDidFinishLoading is called after you have a GPS coordinate.
Or
2) you store the coordinate result of the network connection, and calculate when you got your first coordinate

Try to write location in a text file

I am developing for jailbreak iPhones. I am reading Beginning iOS 5 book. Currently, I have used a location code from the book and changed it slightly. The change which I have made in the code is that I am writing the location in a text file. But the program crashes. Although the same program without any modification is working perfectly.
Here is the code:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = 2.0f;
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
FILE *file = fopen("/usr/locations.txt", "a");
if (!file)
{
fprintf(file, "Error opening file");
}
if (startingPoint == nil)
self.startingPoint = newLocation;
NSString *latitudeString = [NSString stringWithFormat:#"%g\u00B0",
newLocation.coordinate.latitude];
latitudeLabel.text = latitudeString;
NSNumber *latitude = [[NSNumber alloc] initWithDouble:newLocation.coordinate.latitude];
NSNumber *longitude = [[NSNumber alloc] initWithDouble:newLocation.coordinate.longitude];
NSString *longitudeString = [NSString stringWithFormat:#"%g\u00B0",
newLocation.coordinate.longitude];
longitudeLabel.text = longitudeString;
NSString *horizontalAccuracyString = [NSString stringWithFormat:#"%gm",
newLocation.horizontalAccuracy];
horizontalAccuracyLabel.text = horizontalAccuracyString;
NSString *altitudeString = [NSString stringWithFormat:#"%gm",
newLocation.altitude];
altitudeLabel.text = altitudeString;
NSString *verticalAccuracyString = [NSString stringWithFormat:#"%gm",
newLocation.verticalAccuracy];
verticalAccuracyLabel.text = verticalAccuracyString;
CLLocationDistance distance = [newLocation
distanceFromLocation:startingPoint];
NSString *distanceString = [NSString stringWithFormat:#"%gm", distance];
distanceTraveledLabel.text = distanceString;
struct tm *local;
time_t t;
t = time(NULL);
local = localtime(&t);
fprintf(file, "Local time and Date: %s ", asctime(local));
//----------------- ------------------------------------------------------------
fprintf(file, "Latitude = %lf, Longitude = %lf \n",
newLocation.coordinate.latitude, newLocation.coordinate.longitude);
fclose(file);
}
Your most recent comment on the question says you want to print to the console instead. In order to print on the console you use NSLog(). When you use the format specifier for an object %#, the string substituted for the object is the object’s description method.
To print the location on the console use
NSLog(#"New location: %#", newLocation);
NSLog(#"Old location: %#", oldLocation);
The description method on CLLocation returns “A string of the form ‘latitude, longitude +/- accuracy m (speed kph / heading) # date-time’.”

How to find the nearest 100 meters latitude and longitude depending upon the current location in objective c, Iphone

How to find the nearest 100 meters latitude and longitude depending upon the current location, i have created a database in SQLITE3 which consists of set of latitudes and longitudes and corresponding there location name. Depending upon the current location i want to fetch the nearest 100 meters latitude and longitude in objective C,
I am using the following code to get the Current location,
- (void)viewDidLoad {
[super viewDidLoad];
databaseName = #"searchdata.sql";
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir = [documentPaths objectAtIndex:0];
databasePath = [documentDir stringByAppendingPathComponent:databaseName];
[self checkAndCreateDatabase];
[self readDataFromDatabase];
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
int degrees = newLocation.coordinate.latitude;
double decimal = fabs(newLocation.coordinate.latitude - degrees);
int minutes = decimal * 60;
double seconds = decimal * 3600 - minutes * 60;
NSString *lat = [NSString stringWithFormat:#"%d° %d' %1.4f\"",
degrees, minutes, seconds];
NSLog(#" Current Latitude : %#",lat);
//latLabel.text = lat;
degrees = newLocation.coordinate.longitude;
decimal = fabs(newLocation.coordinate.longitude - degrees);
minutes = decimal * 60;
seconds = decimal * 3600 - minutes * 60;
NSString *longt = [NSString stringWithFormat:#"%d° %d' %1.4f\"",
degrees, minutes, seconds];
NSLog(#" Current Longitude : %#",longt);
//longLabel.text = longt;
}
so how to fetch or how to calculate the surrounding 100 meters latitudes and longitudes and display it.
Thanks for the help I am using the following formula
-(double)kilometresBetweenPlace1:(CLLocationCoordinate2D) place1 andPlace2:(CLLocationCoordinate2D) place2 {
double dlon = convertToRadians([pLong intValue] - [longt intValue]);
double dlat = convertToRadians([pLat intValue] - [lat intValue]);
double a = ( pow(sin(dlat / 2), 2) + cos(convertToRadians([lat intValue]))) * cos(convertToRadians([pLat intValue])) * pow(sin(dlon / 2), 2);
double angle = 2 * asin(sqrt(a));
return angle * RADIO;
}
and getting the following output 8505.369547 on return, i am just confused what is the value i am getting actually.
Perhaps the CoreLocation framework can help you with this issue? It seems the following method is made with your question in mind:
- (id)initCircularRegionWithCenter:(CLLocationCoordinate2D)center radius:(CLLocationDistance)radius identifier:(NSString *)identifier
You could test if a coordinate from your database falls within a region by using the following method:
- (BOOL)containsCoordinate:(CLLocationCoordinate2D)coordinate
I guess the above ain't ideal when your database contains a lot of locations. But perhaps one can filter out a set of locations to test based on some minimum and maximum latitude / longitude values.
Edit: as requested, an example (don't forget to import the CoreLocation framework):
- (void)startTest
{
#define COORDS_COUNT 4
#define RADIUS 10000.0f
CLLocationCoordinate2D coords[COORDS_COUNT] = {
CLLocationCoordinate2DMake(52.000004, 4.100002),
CLLocationCoordinate2DMake(53.000009, 4.000003),
CLLocationCoordinate2DMake(52.000001, 4.500008),
CLLocationCoordinate2DMake(52.000002, 3.900900),
};
CLLocationCoordinate2D center = CLLocationCoordinate2DMake(52.0f, 4.0f); // Amsterdam
CLRegion *region = [[CLRegion alloc] initCircularRegionWithCenter:center radius:RADIUS identifier:#"Amsterdam"];
for (int i = 0; i < COORDS_COUNT; i++)
{
CLLocationCoordinate2D coord = coords[i];
if ([region containsCoordinate:coord])
{
NSLog(#"location %f, %f is within %.0f meters of coord %f, %f", coord.latitude, coord.longitude, RADIUS, center.latitude, center.longitude);
}
else
{
NSLog(#"location %f, %f is not within %.0f meters of coord %f, %f", coord.latitude, coord.longitude, RADIUS, center.latitude, center.longitude);
}
}
}
Edit 2: I realize it's not exactly the answer you requested, but it seems to me this is what you need. As you can imagine the nearest 100 meters latitude / longitude near any coordinate consists of an virtually unlimited amount of coordinates in a circular region. My guess is you want to find objects within your database that are nearby some coordinate and the above code should help you achieve this. You can retrieve a set of results from your database and test if they are nearby some coordinate.
Edit 3: The following code is likely exactly what you need:
CLLocation *center = [[CLLocation alloc] initWithLatitude:52.0f longitude:4.0f]; // Amsterdam
CLLocation *location1 = [[CLLocation alloc] initWithLatitude:52.000004f longitude:4.100002f];
CLLocationDistance distance = [center distanceFromLocation:location1];
NSLog(#"%f", distance);
Edit 4: with regards to your question about the custom object for your table view, use something like this:
#interface Location : NSObject
#property (nonatomic, strong) NSString *name;
#property (nonatomic, assign) CLLocationCoordinate2D coordinate;
#end
#implementation Location
#synthesize name, coordinate;
#end

Passing Current longitude & latitude on buttonclick event

Hello I am using CoreLocation to get latitude and longitude in my map application to get latitude and longitude by using following method
- (void)viewDidLoad {
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation];
[super viewDidLoad];
}
The _ (void)locationManager.... method is not getting call
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
int degrees = newLocation.coordinate.latitude;
double decimal = fabs(newLocation.coordinate.latitude - degrees);
int minutes = decimal * 60;
double seconds = decimal * 3600 - minutes * 60;
NSString *lat = [NSString stringWithFormat:#"%d° %d' %1.4f\"",
degrees, minutes, seconds];
degrees = newLocation.coordinate.longitude;
decimal = fabs(newLocation.coordinate.longitude - degrees);
minutes = decimal * 60;
seconds = decimal * 3600 - minutes * 60;
NSString *longt = [NSString stringWithFormat:#"%d° %d' %1.4f\"",
degrees, minutes, seconds];
}
I want to call lati & longi on Button click event to URL. But it is not working. it passes 0000.0 lati & longi to my url. Can some one tell me how to rectify this code
I don't see any obvious problem with your init of CLLocationManager. If you are not getting callbacks perhaps it doesn't yet have a location available. You should also implement the error callback and see if it is getting called instead.
I suggest you try one of the CLLocationManager examples provided by Apple and see if you can get the example to run.
I have did this to pass latitude and longitude in to web service URL on button click...
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
if((fabs(newLocation.coordinate.latitude) > 0.001) || (fabs(newLocation.coordinate.longitude) > 0.001)) {
NSLog(#"Got location %f,%f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
if (currentLocation != nil) {
[currentLocation release];
}
currentLocation = newLocation;
[currentLocation retain];
}}
and On click event code I have just pass locationmanager.location.coordinate.latitude.....
NSString *url = [NSString stringWithFormat:#"http://.....Url..../hespdirectory/phpsqlsearch_genxml.php?lat=%f&lng=%f&radius=%f",locationManager.location.coordinate.latitude,locationManager.location.coordinate.longitude,radius];
U can directly change the CLLocation to NSString
NSString *lat=[NSString stringWithFormat:#"%f", newLocation.latitude];
NSString *lon=[NSString stringWithFormat:#"%f", newLocation.longitude];
The answers don't show it directly, but you should have assigned your controller as the CLLocationManagerDelegate to recieve the callbacks correct?

Using Map Kit how can I find my location?

I need to display my current position in Map Kit, how can I do this ?
self.map.showsUserLocation = TRUE;
is not showing my location instead a point somewhere else in the map? I need to find the location from where I am accessing the application.
Please help me in this..
Thanks in advance
You need to use location manager for getting your current location. And then get the lat long value and create a annonation and display on map. If you use map.showsUserLocation = TRUE; it will show your current location in actual device.
Note - In simulator map kit shows apple's head quarter location somewhere in Cupertino - I don't remember exactly.
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
int degrees = newLocation.coordinate.latitude;
double decimal = fabs(newLocation.coordinate.latitude - degrees);
int minutes = decimal * 60;
double seconds = decimal * 3600 - minutes * 60;
NSString *lat = [NSString stringWithFormat:#"%d° %d' %1.4f\"",degrees, minutes, seconds];
latLabel.text = lat;
degrees = newLocation.coordinate.longitude;
decimal = fabs(newLocation.coordinate.longitude - degrees);
minutes = decimal * 60;
seconds = decimal * 3600 - minutes * 60;
NSString *longt = [NSString stringWithFormat:#"%d° %d' %1.4f\"",
degrees, minutes, seconds];
longLabel.text = longt;
MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } };
region.center.latitude = newLocation.coordinate.latitude;
region.center.longitude = newLocation.coordinate.longitude;
region.span.longitudeDelta = 0.01f;
region.span.latitudeDelta = 0.01f;
[mapView setRegion:region animated:YES];
[mapView setDelegate:self];
}