CLLocationManager always locates London - iphone

I have the following lines of code to locate my position, but I always get the the same location regardless of where I am:
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
[locationManager startUpdatingLocation];
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation *location = [locations lastObject];
self.lati = [NSString stringWithFormat:#"%f",location.coordinate.latitude];
self.longi = [NSString stringWithFormat:#"%f",location.coordinate.longitude];
[locationManager stopUpdatingLocation];
locationManager.delegate = nil;
}

in .h write
<CLLocationManagerDelegate>
then this also
CLGeocoder *geocoder;
CLLocationManager *locationManager;
then in .m
locationManager = [[CLLocationManager alloc] init] ;
locationManager.delegate = self;
[CLLocationManager locationServicesEnabled];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLHeadingFilterNone;
[locationManager startUpdatingLocation];
and then implement its delegates
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation(CLLocation*)newLocation fromLocation:(CLLocation *)oldLocation
{
[manager stopUpdatingLocation];
userCoordinate=newLocation.coordinate;
[[NSUserDefaults standardUserDefaults] setFloat:userCoordinate.latitude
forKey:#"userLat"];
[[NSUserDefaults standardUserDefaults] setFloat:userCoordinate.longitude
forKey:#"userLong"];
CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
[geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
for (CLPlacemark * placemark in placemarks)
{
NSString *cityName = #"";
NSString *countryName = #"";
cityName = [placemark.addressDictionary valueForKey:#"City"];
countryName = [placemark.addressDictionary valueForKey:#"Country"];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:cityName forKey:#"CityName"];
[prefs setObject:countryName forKey:#"CountryName"];
}
}];
[manager stopUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
[manager stopUpdatingLocation];
if(error.code == kCLErrorDenied)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Warning" message:#"You have to select \"Allow\" for current location." delegate:self cancelButtonTitle:#"Ok"
otherButtonTitles: nil];
alert.tag = 888;
[alert show];
}
[[NSUserDefaults standardUserDefaults] setFloat:0.0
forKey:#"userLat"];
[[NSUserDefaults standardUserDefaults] setFloat:0.0
forKey:#"userLong"];
[manager stopUpdatingLocation];
}

Use this delegate method in place of your delegate method. It will work for you.
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
myLatitude = newLocation.coordinate.latitude;
myLongitude = newLocation.coordinate.longitude;
NSLog(#"LAT AND LON IS %f %f",myLatitude,myLongitude);
}

Related

CLGeocoder not working

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after app launch
[window addSubview:viewController.view];
[window makeKeyAndVisible];
[window addViewForTouchPriority:viewController.view];
if(self.locationManager==nil){
locationManager=[[CLLocationManager alloc] init];
locationManager.delegate=self;
locationManager.purpose = #"We will try to tell you where you are if you get lost";
locationManager.desiredAccuracy=kCLLocationAccuracyBest;
locationManager.distanceFilter=500;
self.locationManager=locationManager;
}
geoCoder = [[CLGeocoder alloc] init];
if([CLLocationManager locationServicesEnabled]){
[self.locationManager startUpdatingLocation];
}
return YES;
}
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
lati = [[NSString alloc] initWithFormat:#"%+.6f", newLocation.coordinate.latitude];
NSLog(#"address:%#",lati);
longi = [[NSString alloc] initWithFormat:#"%+.6f", newLocation.coordinate.longitude];
NSLog(#"address:%#",longi);
CLLocationCoordinate2D coord;
coord.latitude = [lati doubleValue];
coord.longitude = [longi doubleValue];
[geoCoder reverseGeocodeLocation: newLocation completionHandler: ^(NSArray *placemarks, NSError *error)
{
//Get nearby address
CLPlacemark *placemark = [placemarks objectAtIndex:0];
//String to hold address
NSString *locatedAt = [[placemark.addressDictionary valueForKey:#"FormattedAddressLines"] componentsJoinedByString:#", "];
//Print the location to console
NSLog(#"I am currently at %#",locatedAt);
address = [[NSString alloc]initWithString:locatedAt];
NSLog(#"address:%#",address);
}];
}
I am using above code to get address by giving latitude and longitude, but control is not entering in to geocoder method, it skips it. Can anybody help me in it.
Thanks in advance.
It doesn't matter, control does not enter in the method, but it works, note the output it will work.
that is normal, because the code inside the reverseGeocodeLocation is execute inside a block.
The execution of the code inside a block occurs in another thread, so is not execute in the main thread, that's why the control don't enter inside the geocoder method.

Error in getting current country

I am using following code to get current country
NSLocale *locale = [NSLocale currentLocale];
NSString *countryCodes = [locale objectForKey:NSLocaleCountryCode];
NSString *countryName = [locale displayNameForKey:NSLocaleCountryCode value:countryCodes];
NSLog(#"%#",countryName);
I am in UAE , but this is showing United States , I testing on my iPod , please help how Can I get current country ?
-(void)viewWillAppear:(BOOL)animated
{
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
[super viewWillAppear:animated];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
MKReverseGeocoder *geoCoder = [[MKReverseGeocoder alloc] initWithCoordinate:newLocation.coordinate];
geoCoder.delegate = self;
[geoCoder start];
}
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark
{
NSLog(#"Detail is:--> %#",placemark);
NSString *strCountry = [NSString stringWithFormat:#"Current Cuntry %#",[placemark.addressDictionary objectForKey:#"Country"]];
NSLog(#"label detail is:--> %#",strCountry);
lblAddress.text = strCountry;
}
Try this code...This will definately give you a current country detail.

How to get locationManager startMonitoringSignificantLocationChanges accurate readings

Hi I have a requirement where I need to update user's location to the server while app is running in the background. I have used the code below to test it in the car and have found few discrepancies in the lat and long that are reported when the - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation: is fired.The coordinates are way far of to where I actually am at that moment.
I know the didupdatelocation uses cell tower readings hence not very accurate.I was wondering if there is anyway I can start [locationManager startUpdatingLocation] when the - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:; and then get the readings which are much more accurate.
Please any help or directions would be great and highly appreciated.
#import "LocationsAppDelegate.h"
#import "RootViewController.h"
#implementation LocationsAppDelegate
#synthesize window;
#synthesize navigationController;
-(void)initLocationManager {
if (locationManager == nil) {
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters; // 100 m
// [locationManager startUpdatingLocation];
[locationManager startMonitoringSignificantLocationChanges];
}
}
- (void)saveCurrentData:(NSString *)newData {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *savedData = [[NSMutableArray alloc] initWithArray:[defaults objectForKey:#"kLocationData"]];
[savedData addObject:newData];
[defaults setObject:savedData forKey:#"kLocationData"];
[savedData release];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSDate* eventDate = newLocation.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
//check if the data is less than 15 sec ago
if (abs(howRecent) > 15.0)
{
NSLog(#"old data latitude %+.6f, longitude %+.6f\n",
newLocation.coordinate.latitude,newLocation.coordinate.longitude);
}else{
[locationManager startUpdatingLocation];
NSDateFormatter * formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setTimeStyle:NSDateFormatterMediumStyle];
NSString *locationData = [NSString stringWithFormat:#"%.6f, %.6f, %#",newLocation.coordinate.latitude, newLocation.coordinate.longitude,[formatter stringFromDate:newLocation.timestamp]];
[self saveCurrentData:locationData];
[locationManager stopUpdatingLocation];
}
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
NSString *errorData = [NSString stringWithFormat:#"%#",[error localizedDescription]];
NSLog(#"%#", errorData);
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
if (![CLLocationManager significantLocationChangeMonitoringAvailable]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Sorry" message:#"Your device won't support the significant location change." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
return YES;
}
[self initLocationManager];
[self.window addSubview:navigationController.view];
[self.window makeKeyAndVisible];
return YES;
}
- (void)dealloc {
[locationManager release];
[navigationController release];
[window release];
[super dealloc];
}
#end
The behaviour of startMonitoringSignificantLocationChanges is not affected by the distanceFilter or desiredAccuracy properties.
So if you want to retrieve more accurated results, call startUpdatingLocation, and by playing with the distanceFilter and desiredAccuracy properties (kCLLocationAccuracyBestForNavigation, kCLLocationAccuracyBest) are the most accurated, but consumes more power, so play with them.
I didn't understand exactly the behaviour of your code. Why you call startMonitoringSignificantLocationChanges instead of startUpdatingLocation, but you call it inside the delegate method?

How do I get the current location from the location manager?

i want my app to get the exact location (longitude and latitude) of where he is as every second, it is possible ? i have this code so far, every 3 second the app get the current location but it doesnt update if i move...
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
NSLog(#"lol");
[locationManager stopUpdatingLocation];
if (wtf == 2) {
[[NSUserDefaults standardUserDefaults] setObject:newLocation forKey:#"old"];
NSLog(#"wtf");
wtf =0;
}
oldLocation = [[NSUserDefaults standardUserDefaults] objectForKey:#"old"];
double rep = [oldLocation distanceFromLocation:newLocation];
NSString *label1 = [NSString stringWithFormat:#"%2.90f",oldLocation.coordinate.latitude];
NSString *label2 = [NSString stringWithFormat:#"%2.90f",newLocation.coordinate.latitude];
if ([label1 isEqual:label2]) {
NSLog(#"penis");
}
labelm.text = label1;
labelkm.text = label2;
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
}
-(void)actualise{
[locationManager startUpdatingLocation];
}
- (void)viewDidLoad {
[super viewDidLoad];
wtf = 2;
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
[NSTimer scheduledTimerWithTimeInterval:3 target:self selector:#selector(actualise) userInfo:nil repeats:YES];
}
/*
Use this code to initialize and start the location manager:
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
[locationManager startUpdatingLocation];
And implement didUpdateToLocation like this:
- (void) locationManager:(CLLocationManager*)manager didUpdateToLocation:(CLLocation*)newLocation fromLocation:(CLLocation*) oldLocation
{
// This will be called every time the device has any new location information.
}
There is no need to use any timers.

CLLocationDistance: Cant get "getDistanceFrom" to work

view based app,
.m
- (void)viewDidLoad {
[super viewDidLoad];
self.locationManager = [[[CLLocationManager alloc] init] autorelease];
self.locationManager.delegate = self;
[[self locationManager] startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
CurrentLocation = newLocation;
[locationManager stopUpdatingLocation];
myActivity.hidden=YES;
[self reStart];
}
-(void)reStart{
[self checkAndCreateDatabase]; //Sucess
[self readFromDatabase]; //Success if I comment the get distance part
[self sort]; //Success
}
-(void) readFromDatabase {
...
CLLocationCoordinate2D cord;
cord.latitude = [[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)] doubleValue];
cord.longitude =[[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)] doubleValue];
NSDate *today = [NSDate date];
CLLocation *objectLocation = [[CLLocation alloc] initWithCoordinate:cord altitude:1 horizontalAccuracy:1 verticalAccuracy:-1 timestamp:today];
CLLocationDistance distance = [objectLocation getDistanceFrom:CurrentLocation]/1000;
NSLog([NSString stringWithFormat:#"%.0f", distance]);
}
What is wrong?
debugger says:
obj_msgSend
0x912e8688 <+0024> mov 0x20(%edx),%edi
object from database:
long: 59.291114
lat: 17.816191
Use distanceFromLocation: instead
Is CurrentLocation an instance-variable/property? You are setting it directly without an accessor and you are not retaining it. If it is released before you use it in getDistance: it will cause a crash.
If it is a property use the self.CurrentLocation to ensure it is retained.
Also, the construction...
NSLog([NSString stringWithFormat:#"%.0f", distance]);
... is risky and redundant. Use...
NSLog(#"%.0f", distance);
... instead.