user391686
user391686

Reputation: 107

iOS CoreLocation not getting GPS coordinates

So I am new to iOS development, and I am just trying to get a label updated with my current GPS Coordinates. I am not having an issue compiling, but my coordinates are coming up as 0.00000, 0.00000.

Here is the code for my .h file:

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>


@interface ViewController : UIViewController{
    IBOutlet CLLocationManager *locationManager;
    IBOutlet UILabel *location;
}

//@property (nonatomic, retain) IBOutlet CLLocationManager *locationManager;
//@property (weak, nonatomic) IBOutlet UILabel *location;
@end

Here is the code for my .m file:

@implementation ViewController

- (void) updateLabel
{
    NSObject *latitude = [NSString stringWithFormat:@"%f", locationManager.location.coordinate.latitude];
    NSObject *longitude = [NSString stringWithFormat:@"%f", locationManager.location.coordinate.longitude];

    location.text = [NSString stringWithFormat: @"%@,%@", latitude, longitude];
}

- (void)viewDidLoad
{

    locationManager = [[CLLocationManager alloc] init];
    locationManager.distanceFilter = kCLDistanceFilterNone;
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
    [self updateLabel];
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

Upvotes: 0

Views: 2825

Answers (4)

Narayan Bhandari
Narayan Bhandari

Reputation: 426

I find this is fascinating to use location as singleton, and save the values into default user . I am young programmer and am trying to code all in oop. I use this as follow ( this code still need to be refactored and alertUserWithTitle: is a class method of NYMessageToUser to alert user):

//##Header file:
@interface NYLocationManager : NSObject<CLLocationManagerDelegate>
{
    CLLocationManager *locationManager;
    float lonngitude;
    float latitude;
    float altitude;
}
@property(nonatomic,retain)CLLocationManager *locationManager;
@property(nonatomic,readwrite)float longitude;
@property(nonatomic,readwrite)float latitude;
@property(nonatomic,readwrite)float altitude;

+(NYLocationManager *) getInstance;

-(void)startUpdatingLocation;
-(void)stopUpdatingLocation;
-(double)getDistanceFromUserLocationToCordinatesLatitude:(float)lat Longitude:(float)lon;

@end




//### implementation file: 

@implementation NYLocationManager

@synthesize locationManager;
@synthesize latitude;
@synthesize longitude;
@synthesize altitude;

+ (id)getInstance
{
    static NYLocationManager *Instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Instance = [[self alloc] init];
    });
    [Instance startUpdatingLocation];
    return Instance;
}

- (id)init
{
    if (self = [super init])
    {

        latitude    =0.0;
        longitude   =0.0;
        altitude    =0.0;
        if([[NSUserDefaults standardUserDefaults] objectForKey:@"locationLongitude"] != nil)
        {
            NSUserDefaults *savedLocation=[NSUserDefaults standardUserDefaults];
            latitude    =[[savedLocation objectForKey:@"locationLatitude"] floatValue];
            longitude   =[[savedLocation objectForKey:@"locationLongitude"] floatValue];
            altitude    =[[savedLocation objectForKey:@"locationAltitude"] floatValue];
        }
        locationManager = [[CLLocationManager alloc] init];
        locationManager.distanceFilter  = kCLDistanceFilterNone;
        locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
        locationManager.delegate        = self;
        if ([CLLocationManager locationServicesEnabled])
        {
            [locationManager startUpdatingLocation];
        } else
        {
            [NYMessageToUser  alertUserWithTitle:@"Location Services is Disabled!!!" withMessage:@"This app is designed to share images with location, Please enable location for this app and relucnh the app"];
        }
    }
    return self;
}

- (void)dealloc
{
    // Should never be called, but just here for clarity really.
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *loc =[locations lastObject];
    self.longitude  =loc.coordinate.longitude;
    self.latitude   =loc.coordinate.latitude;
    self.altitude   =loc.altitude;
    NSUserDefaults *savedLocation=[NSUserDefaults standardUserDefaults];
    [savedLocation setObject: [NSString stringWithFormat:@"%f", self.longitude] forKey:@"locationLongitude"];
    [savedLocation setObject: [NSString stringWithFormat:@"%f", self.latitude] forKey:@"locationLatitude"];
    [savedLocation setObject: [NSString stringWithFormat:@"%f", self.altitude ] forKey:@"locationAltitude"];
    [savedLocation synchronize];

    [locationManager stopUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    [locationManager stopUpdatingLocation];
    [NYMessageToUser alertUserWithTitle:@"Location Error!!!" withMessage:@"This app is designed to use with valid location, Please enable location for this app and relucnh the app"];
}
-(void)startUpdatingLocation
{
    if ([CLLocationManager locationServicesEnabled])
    {
        [locationManager startUpdatingLocation];
    } else
    {
        [NYMessageToUser alertUserWithTitle:@"Location Services is Disabled!!!" withMessage:@"This app is designed to share images with location, Please enable location for this app and relucnh the app"];
    }
}

-(void)stopUpdatingLocation
{
    [locationManager stopUpdatingLocation];
}
-(double)getDistanceFromUserLocationToCordinatesLatitude:(float)lat Longitude:(float)lon
{
    CLLocation *locA = [[CLLocation alloc] initWithLatitude:self.latitude longitude:self.longitude];

    CLLocation *locB = [[CLLocation alloc] initWithLatitude:lat longitude:lon];

    CLLocationDistance distance = [locA distanceFromLocation:locB];
    return distance;
}
@end 




//### How to use



NYLocationManager *loc  =[NYLocationManager getInstance];
 NSLog(@"longitude: %f, latitude: %f, altitude: %f",loc.longitude,loc.latitude,loc.altitude);

Upvotes: 0

iSpark
iSpark

Reputation: 952

once try like this,in ViewDidLoad:

    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = (id)self;
    locationManager.distanceFilter = kCLDistanceFilterNone;
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
    [locationManager startUpdatingLocation];
    [self updateLabel];

Use this Delegate Method otherwise you will get 0 values:

 - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
   //No need to do any code...
   // NSLog(@"Got location %f,%f", newLocation.coordinate.latitude,   newLocation.coordinate.longitude);

 }

In Updating Label Method :

- (void) updateLabel
{
   //Getting Current Latitude and longitude..

    CLLocation *location = [locationManager location];
    float longitude=location.coordinate.longitude;
    float latitude=location.coordinate.latitude;
    NSLog(@"latitude,longitudes are >> %f,%f",latitude,longitude);
    locationlabel.text =  [NSString stringWithFormat:@"%f,%f",longitude,latitude];


  } 

Upvotes: 1

user391686
user391686

Reputation: 107

Fixed it:

I wasn't implementing any delegate methods, and I was not implementing [locationManager startUpdatingLocation]. Now I know better.

.h File:

@interface MapViewController : UIViewController <CLLocationManagerDelegate>
@property (nonatomic, retain) IBOutlet CLLocationManager *locationManager;
@property (strong, nonatomic) IBOutlet UILabel *location;
@end

.m File:

- (void) updateCurrentLabel
{
    NSObject *latitude = [NSString stringWithFormat:@"%f", locationManager.location.coordinate.latitude];
    NSObject *longitude = [NSString stringWithFormat:@"%f", locationManager.location.coordinate.longitude];

    self.location.text = [NSString stringWithFormat: @"Current Location: %@,%@", latitude, longitude];
}

- (void)viewDidLoad
{
    [self getCurrentLocation];
    [super viewDidLoad];
}
-(void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    [self updateCurrentLabel];
}

-(void) getCurrentLocation
{
    self.locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
    locationManager.distanceFilter = kCLDistanceFilterNone;
    [locationManager startUpdatingLocation];
}

Thanks for pointing out how nooby I was. Figured it out. Thanks guys!

Upvotes: 1

nevan king
nevan king

Reputation: 113777

Instead of using locationManager.location.coordinate.latitude, keep an instance variable of type CLLocationCoordinate2D. You can call it something like currentLocation. Then when you get a value in the delegate method locationManager:didUpdateLocations:, set the value of currentLocation.

You'll have to call [locationManager startUpdatingLocation] and set its delegate too (as well as implementing that delegate method).

The way you're using the location manager at the moment is wrong and I think you'd be better off following a tutorial to get the basics down.

Upvotes: 0

Related Questions