best way to get changed location iPhone sdk? - iphone

My ultimate goal is that i need to send lat and logitude to web server, every time when location changes.
I am using below code for sending lat and longitude of a device to a web server after every 2 minutes but it is not giving sometimes correct latitude and longitude as location changes.
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation
*)newLocation fromLocation:(CLLocation *)oldLocation
{
NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
NSLog(#"Location Age%#",[NSString stringWithFormat:#"%d",locationAge]);
if (locationAge > 5) return;
// test that the horizontal accuracy does not indicate an invalid measurement
if (newLocation.horizontalAccuracy < 0) return;
NSString *stringUrl;
// BOOL check = FALSE;
NSLog(#"Before condition condition");
if(bestEffortAtLocation == nil || bestEffortAtLocation.horizontalAccuracy > newLocation.horizontalAccuracy){
NSLog(#"condition");
self.bestEffortAtLocation = newLocation;
if (newLocation.horizontalAccuracy <= locmanager.desiredAccuracy) {
// we have a measurement that meets our requirements, so we can stop updating the location
// IMPORTANT!!! Minimize power usage by stopping the location manager as soon as possible.
[locmanager stopUpdatingLocation];
locmanager.delegate = nil;
}
//check = TRUE;
}
stringUrl = [NSString stringWithFormat:URLSAVELAT,stringUserId,[NSString stringWithFormat:#"%g",self.bestEffortAtLocation.coordinate.latitude],[NSString stringWithFormat:#"%g",self.bestEffortAtLocation.coordinate.longitude]];}
For location manager i am using below code
{
locmanager = [[CLLocationManager alloc] init];
[locmanager setDelegate:self];
locmanager.distanceFilter = 10.0;
//locmanager.distanceFilter = kCLDistanceFilterNone;
[locmanager setDesiredAccuracy:kCLLocationAccuracyBest];
[locmanager startUpdatingLocation];
}
Any,even small help would be appreciated, Thank u in advance

You should use the location update call backs from the API and use updateLocation method:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
if([self.delegate conformsToProtocol:#protocol(CoreLocationControllerDelegate)]) {
[self.delegate locationUpdate:newLocation];
}
}
Then in the viewcontroller do this:
- (void)locationUpdate:(CLLocation *)location {
//DO WHATEVER YOU WANT HERE, INCLUDING SENDING TO SERVER
}
You also need to define two protocol methods, one of which is the locationUpdate:
#protocol CoreLocationControllerDelegate
#required
- (void)locationUpdate:(CLLocation *)location;
- (void)locationError:(NSError *)error;
#end
I would not recommend doing all that you do in the didUpdateLocation: method.

Related

Getting latitude and longitude in IOS7

I am developing an iPhone app which uses location services and runs in background.This app displays latitude and longitude exactly when it runs on IOS6.But if i run the same app on IOS7, sometimes it shows latitude and longitude exactly, sometimes -1 and -1. I'm not understanding this behaviour on IOS7. what may be the reason for this behaviour?
In order to simulate a location, select the iOS Simulator Debug -> Location menu option and select either one of the pre-defined locations or journeys (such as City Bicycle Ride), or Custom Location… to enter a specific latitude and longitude.
This code worked for me.
Creating the CLLocationManager Object
The next task is to implement the code to create an instance of the CLLocationManager class. Since this needs to occur when the view loads, an ideal location is in the view controller’s viewDidLoad method in the LocationViewController.m file:
- (void)viewDidLoad {
[super viewDidLoad];
_locationManager = [[CLLocationManager alloc] init];
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
_locationManager.delegate = self;
[_locationManager startUpdatingLocation];
_startLocation = nil;
}
Implementing the Action Method
-(void)resetDistance:(id)sender
{
_startLocation = nil;
}
Implementing the CLLocationManager Method
#pragma mark -
#pragma mark CLLocationManagerDelegate
-(void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
NSString *currentLatitude = [[NSString alloc]
initWithFormat:#"%+.6f",
newLocation.coordinate.latitude];
_latitude.text = currentLatitude;
NSString *currentLongitude = [[NSString alloc]
initWithFormat:#"%+.6f",
newLocation.coordinate.longitude];
_longitude.text = currentLongitude;
NSString *currentHorizontalAccuracy =
[[NSString alloc]
initWithFormat:#"%+.6f",
newLocation.horizontalAccuracy];
_horizontalAccuracy.text = currentHorizontalAccuracy;
NSString *currentAltitude = [[NSString alloc]
initWithFormat:#"%+.6f",
newLocation.altitude];
_altitude.text = currentAltitude;
NSString *currentVerticalAccuracy =
[[NSString alloc]
initWithFormat:#"%+.6f",
newLocation.verticalAccuracy];
_verticalAccuracy.text = currentVerticalAccuracy;
if (_startLocation == nil)
_startLocation = newLocation;
CLLocationDistance distanceBetween = [newLocation
distanceFromLocation:_startLocation];
NSString *tripString = [[NSString alloc]
initWithFormat:#"%f",
distanceBetween];
_distance.text = tripString;
}
In the End Try this method
Try this method to get continuous updated latitude and longitude
(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *location_updated = [locations lastObject];
NSLog(#"updated coordinate are %#",location_updated);
}
Use this method for getting location continuously use this method
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
location_updated = [locations lastObject];
NSLog(#"updated coordinate are %#",location_updated);
}
may be you are using this method
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
This method has been Deprecated in iOS 6.0

CLLocationManager issue

I want to get a single location and then stop getting notification from CLLocationManager.
I do it with this:
-(id)initWithDelegate:(id <GPSLocationDelegate>)aDelegate{
self = [super init];
if(self != nil) {
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
delegate = aDelegate;
}
return self;
}
-(void)startUpdating{
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
[locationManager stopUpdatingLocation];
[delegate locationUpdate:newLocation];
}
The issue is that even when I do [locationManager stopUpdatingLocation];
in - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:
I still get notification, any idea why it happen?
Maybe try my solution. I'm build two functionals for handling LocationManger Obj.
The first function is startUpdates for handle start update location. Code look like this :
- (void)startUpdate
{
if ([self locationManager])
{
[[self locationManager] stopUpdatingLocation];
}
else
{
self.locationManager = [[CLLocationManager alloc] init];
[[self locationManager] setDelegate:self];
[[self locationManager] setDesiredAccuracy:kCLLocationAccuracyBestForNavigation];
[[self locationManager] setDistanceFilter:10.0];
}
[[self locationManager] startUpdatingLocation];
}
The second function is stopUpdate for handle CLLocationDelegate to stop update location. Code look like this :
- (void)stopUpdate
{
if ([self locationManager])
{
[[self locationManager] stopUpdatingLocation];
}
}
So, for CLLocationManagerDelegate should be look like this :
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
NSDate* eventDate = newLocation.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
self.attempts++;
if(firstPosition == NO)
{
if((howRecent < -2.0 || newLocation.horizontalAccuracy > 50.0) && ([self attempts] < 5))
{
// force an update, value is not good enough for starting Point
[self startUpdates];
return;
}
else
{
firstPosition = YES;
isReadyForReload = YES;
tempNewLocation = newLocation;
NSLog(#"## Latitude : %f", tempNewLocation.coordinate.latitude);
NSLog(#"## Longitude : %f", tempNewLocation.coordinate.longitude);
[self stopUpdate];
}
}
}
Inside this function above, i'm correct only the best location for update location. I hope my answer will help, Cheers.
I think that the reason of your problem is in distance filter. As docs say:
Use the value kCLDistanceFilterNone to be notified of all movements. The default value of this property is kCLDistanceFilterNone.
So you just have what you've set - continuous updates.

CLLocationManager didUpdateToLocation checking failing

I am trying to get the location coordinates using CLLocationManager. Here is my code
- (void)viewDidLoad {
[super viewDidLoad];
//instantiate location manager and set delegate
self.locationManager=[[CLLocationManager alloc]init];
locationManager.delegate=self;
// can be set to 100m,1km,3km etc.
//locationManager.distanceFilter=10.0f;
locationManager.desiredAccuracy=kCLLocationAccuracyNearestTenMeters;
//start updating the delegate
[locationManager startUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation{
// Check if the coordinates are different from the old ones
if (newLocation.coordinate.latitude != oldLocation.coordinate.latitude &&
newLocation.coordinate.longitude != oldLocation.coordinate.longitude) {
NSLog(#"not equal");
} else {
NSLog(#"equal");
}
}
However i find the condition is called twice. First time the condition is satisfied and prints not equal and immediately its called again and prints "equal". Can some1 help me out ? What am i doing wrong ?
Thanks
This is because CoreLocation cache your last location and return it immediately after you called startUpdatingLocation so you have to validate coordinate timestamp and it is too old, you can ignore old coordinate.
UPDATE:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
if([newLocation horizontalAccuracy] < 0.0f) return;
if(fabs([[newLocation timestamp] timeIntervalSinceNow]) > kCLLocationMaximumLocationDataAge) return;
if(fabs([[oldLocation timestamp] timeIntervalSinceNow]) < kCLLocationMaximumLocationDataAge && [newLocation getDistanceFrom:oldLocation] < 0.1f && [newLocation horizontalAccuracy] == [oldLocation horizontalAccuracy])
return;
if(((runningHighPreciseLocationDetectionService||runningLowPowerLocationDetectionService) && ([newLocation horizontalAccuracy] <= kCLLocationAccuracyHundredMeters))){
NSLog(#"---> \n%#\n%#\nHorizontal accurecy: %f\nLocation age: %fs\nOld location age: %fs", NSStringFromSelector(_cmd), newLocation, newLocation.horizontalAccuracy, fabs([[newLocation timestamp] timeIntervalSinceNow]), fabs([[oldLocation timestamp] timeIntervalSinceNow]));
} else {
NSLog(#"\n-------------- BAD ---------------\n%#\n%#\nHorizontal accurecy: %f\nLocation age: %fs\nOld location age: %fs\n----------------------------------", NSStringFromSelector(_cmd), newLocation, newLocation.horizontalAccuracy, fabs([[newLocation timestamp] timeIntervalSinceNow]), fabs([[oldLocation timestamp] timeIntervalSinceNow]));
}
if(((runningHighPreciseLocationDetectionService||runningLowPowerLocationDetectionService) && ([newLocation horizontalAccuracy] <= kCLLocationAccuracyHundredMeters))){
[self stopLocationImprovementTimer];
} else [self createLocatinoImprovementTimer];
}
createLocatinoImprovementTimer method used to launch timer, which will work for certain amount of time and if it wasn't stopped it will send and update notification with location, which was last. This timer will help to wait for coordinate with better accuracy before notify controllers.

how to get the current location position in map on iphone

i am creating an application in which i want to get the current location of the user where he is and display it on the map and when the user reaches the destination location from current location the destination location should also be pointed in the map along the direction of travel.
In my xib i have added a button & on action(showDirectionsToHere) of button i have called map
I have added the following code in my appdelegate but it gives me an error:
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation{
[manager stopUpdatingLocation];
printf("\n Latitude = " "\n Longitude = " " ",[NSString stringWithFormat:#"%.7f",newLocation.coordinate.latitude],[NSString stringWithFormat:#"%.7f",newLocation.coordinate.longitude]);
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
CLLocationManager *locationManager = [[[CLLocationManager alloc]init]autorelease];
locationManager.delegate = self;
[locationManager startUpdatingLocation];
//[self.window addSubview:viewController.view];
[self.window makeKeyAndVisible];
return YES;
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
printf("\nerror");
}
- (IBAction)showDirectionsToHere {
CLLocationCoordinate2D currentLocation = [self getCurrentLocation]; // LINE 1
NSString* url = [NSString stringWithFormat: #"http://maps.google.com/maps?saddr=old\%20Location&daddr=%f,%f", newLocation.latitude, newLocation.longitude];//Line 2
}
in line 1 of action(showDirectionsHere) i get error of invalid initializer
in Line 2 i get error that newLocation undeclared.
Please help me
NSString* url = [NSString stringWithFormat: #"http://maps.google.com/maps?saddr=old\%20Location&daddr=%f,%f", currentLocation.latitude, currentLocation.longitude];
Can you post the code for getCurrentLocation so that we can see what it returns.
The variable newLocation is undeclared. I think you meant currentLocation in the function.

Trying to get CLLocationCoordinate2D Latitude and Longitude

Hello im trying to get the latitude and longitude values where the the location of the user is
without having the map show up so basically it will run on the background. I guess i have to use the map kit but are there any examples?
If you don't want a map, you don't need MapKit. Just use CLLocationManager.
- (id) init {
if (self = [super init]) {
locationManager = [[CLLocationManager alloc] init];
[locationManager setDelegate:self];
[locationManager startUpdatingLocation];
}
return self;
}
- (void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)location fromLocation:(CLLocation *)oldLocation {
NSLog(#"lat:%f lon:%f", location.coordinate.latitude, location.coordinate.longitude);
}