Getting Longitude/Latitude of the User When the viewDidLoad - ios

My purpose is to get the longitude/latitude of the user when the view is loaded and to store the values in two variables for later calculations. I don't need to track the user location and to update it, I simply need to get his/her coordinates once. My code looks like this:
- (void)viewDidLoad {
[super viewDidLoad];
// locationManager update as location
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
CLLocation *location = [locationManager location];
// Configure the new event with information from the location
CLLocationCoordinate2D coordinate = [location coordinate];
float longitude=coordinate.longitude;
float latitude=coordinate.latitude;
NSLog(#"dLongitude : %f",longitude);
NSLog(#"dLatitude : %f", latitude);
}
In the console i keep getting this:
dLongitude : 0.000000
dLatitude : 0.000000
Can you please help me there?

To get user's location even once you need to make locationManager to start updating locations (you did that) and implement delegate method that manager calls when location is retrieved - you can't get location from location manager immediately.
If you don't want to track user location - just stop updating locations in that delegate method after location was fetched for the 1st time (and store it if you need it in future).

As soon as you call [locationManager startUpdatingLocation]; your viewDidLoad method is done. You need to implement
-(void) locationManager: (CLLocationManager *)manager didUpdateToLocation: (CLLocation *) newLocation
fromLocation: (CLLocation *) oldLocation
and
- (void) locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
which will be called by your locationManager when it gets the location, or when it fails. In both of those methods, you can call [locationManager stopUpdatingLocation].
Inside the didUpdateToLocation method, you should move all your code from viewDidLoad, starting with CLLocation *location = [locationManager location]; That's where you'll get proper values.

This worked for me
- (void)viewDidLoad {
[super viewDidLoad];
// locationManager update as location
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
[locationManager stopUpdatingLocation];
CLLocation *location = [locationManager location];
// Configure the new event with information from the location
float longitude=location.coordinate.longitude;
float latitude=location.coordinate.latitude;
NSLog(#"dLongitude : %f", longitude);
NSLog(#"dLatitude : %f", latitude);
}

Try this Code
-(IBAction)Button:(id)sender
{
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
CLLocation *location = [locationManager location];
// Configure the new event with information from the location
CLLocationCoordinate2D coordinate = [location coordinate];
NSString *latitude = [NSString stringWithFormat:#"%f", coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:#"%f", coordinate.longitude];
NSLog(#"dLatitude : %#", latitude);
NSLog(#"dLongitude : %#",longitude);
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, 40, 250, 50)];
UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 80, 200, 50)];
UILabel *myLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(50, 120, 200, 100)];
myLabel.textColor = [UIColor blackColor];
myLabel1.textColor = [UIColor blackColor];
label.backgroundColor = [UIColor clearColor];
myLabel.backgroundColor = [UIColor clearColor];
myLabel1.backgroundColor = [UIColor clearColor];
[myLabel setText:latitude];
[myLabel1 setText:longitude];
label.text = #"Current Latitude And Longitude";
[self.view addSubview:label];
[self.view addSubview:myLabel];
[self.view addSubview:myLabel1];
}

if you are getting Lat lang both (0.00 ,0.00)
this may be solution for your ,
step 1:
NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription
Add these two key in Info.plist
step 2:
And than [locationManager startUpdatingLocation]; start updating
step 3:
and you need to implement
two mehthods
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
CLLocation * currentLocation = [locations lastObject];
NSLog(#"Updated Lat %f",currentLocation.coordinate.longitude);
NSLog(#"Updated Lang %f",currentLocation.coordinate.latitude);
}
of CLLocationManagerDelegate in your ViewController interface.
**step 4:**
-(void)viewDidLoad
{
[super viewDidLoad];
geocoder = [[CLGeocoder alloc] init];
manager.delegate = self;
manager.desiredAccuracy = kCLLocationAccuracyBest;
[manager requestWhenInUseAuthorization];
[manager requestAlwaysAuthorization];
[manager startUpdatingLocation];
}

Related

How will i get current location of device from google maps.? [duplicate]

This question already has answers here:
How to find your current location with CoreLocation
(3 answers)
Closed 6 years ago.
I am working in google map in my app. i get default location on map currently. but i need to get current location of device an show it on map. There are lots of solution are there on stackoverlfow, but somehow its not working in my case. These solution work if i add map on default view.Look at my little bit code.
.h file
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import GoogleMaps;
#interface ViewController : UIViewController<CLLocationManagerDelegate, GMSMapViewDelegate>
#property (weak, nonatomic) IBOutlet UIView *maponScreem;
#property (nonatomic, retain) CLLocationManager *locationManager;
#end
.m file
self.locationManager.delegate = self;
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.distanceFilter = kCLDistanceFilterNone;
self.locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[self.locationManager startUpdatingLocation];
latitude = [NSString stringWithFormat:#"%f",self.locationManager.location.coordinate.latitude];
longtitude = [NSString stringWithFormat:#"%f",self.locationManager.location.coordinate.longitude];
NSLog(#"%#", latitude);
NSLog(#"%#", longtitude);
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:[latitude floatValue]
longitude:[longtitude floatValue]
zoom:12];
mapView_ = [GMSMapView mapWithFrame:self.maponScreem.bounds camera:camera];
mapView_.delegate = self;
mapView_.myLocationEnabled = YES;
[self.maponScreem addSubview: self->mapView_];
// Creates a marker in the center of the map.
GMSMarker *marker = [[GMSMarker alloc] init];
marker.position = CLLocationCoordinate2DMake([latitude intValue], [longtitude intValue]);
marker.title = #"Current Location";
marker.map = mapView_;
i get 0.000000 for attitude and longitude.
EDIT:
i found solution and look at this how it works. Thanks to you all for answers and support me.
- (void)viewDidLoad {
[super viewDidLoad];
if (self.locationManager == nil)
{
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
}
else
{
nil;
}
if ([self.locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)])
{
[self.locationManager requestWhenInUseAuthorization];
}
else
{
nil;
}
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[self.locationManager startUpdatingLocation];
GMSCameraPosition *camera = [GMSCameraPosition cameraWithTarget:CLLocationCoordinate2DMake(0, 0) zoom: 16];
mapView_ = [GMSMapView mapWithFrame:self.maponScreem.bounds camera:camera];
mapView_.myLocationEnabled = YES;
[self.maponScreem addSubview: self->mapView_];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *location = [locations lastObject];
NSString *lasti = [NSString stringWithFormat:#"%f", location.coordinate.latitude];
NSString *longi = [NSString stringWithFormat:#"%f", location.coordinate.longitude];
// NSLog(#"%#", lat);
// NSLog(#"%#", longi);
[mapView_ animateToLocation:location.coordinate];
}
You have not initialized your locationManager and also you need to ask user permission for location access and set its delegate.Use following code before starting location updates.
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
if ([self.locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]) {
[self.locationManager requestWhenInUseAuthorization]; //gives alert for location access
}
It will give you user location.
Hope it helps :)
EDIT
You should use below method to receive location updates
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray<CLLocation *> *)locations
The method you have used is deprecated.
#property (nonatomic, retain) IBOutlet GMSMapView *googleMapView;
#property (nonatomic, retain) CLLocationManager *locationManager;
- (void)showCurrentLocation {
_googleMapView.myLocationEnabled = YES;
[self.locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:newLocation.coordinate.latitude
longitude:newLocation.coordinate.longitude
zoom:17.0];
[_googleMapView animateToCameraPosition:camera];
//...
}
I hope this will help you..
- (IBAction)btnSetDistance:(id)sender {
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.pausesLocationUpdatesAutomatically = NO;
locationManager.distanceFilter =//as per your requirment;
if ([locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]) {
[locationManager requestWhenInUseAuthorization];
}
[locationManager startUpdatingLocation];
}
This is important
Enable Background Modes from--- Project, Capabilities Tab, and choose Location Updates...
you should check it on device instead of simulator.

Objective-C issues with Location Manager

I am using Location Manager. Its acting very strange. I have these UILabels in place and I am looking for away to consistently update these UILabels when the coordinates change. This is what I have in place:
#implementation ViewController
{
CLLocationManager *locationManager;
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
locationManager = [[CLLocationManager alloc] init];
[locationManager requestWhenInUseAuthorization];
[locationManager requestAlwaysAuthorization];
currentLocation = nil;
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
and then this:
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *) newLocation
fromLocation:(CLLocation *)oldLocation
{
/*if (currentLocation == nil)
currentLocation = newLocation;
if (currentLocation != nil) {
Longitude = [NSString stringWithFormat:#"%.10f", currentLocation.coordinate.longitude];
Latitude = [NSString stringWithFormat:#"%.10f", currentLocation.coordinate.latitude];
LongitudeDouble = currentLocation.coordinate.longitude;
LatitudeDouble = currentLocation.coordinate.latitude;
}*/
currentLocation = newLocation;
Longitude = [NSString stringWithFormat:#"%.10f", currentLocation.coordinate.longitude];
Latitude = [NSString stringWithFormat:#"%.10f", currentLocation.coordinate.latitude];
LongitudeDouble = currentLocation.coordinate.longitude;
LatitudeDouble = currentLocation.coordinate.latitude;
Long.text = [NSString stringWithFormat:#"%.10f", LongitudeDouble];
Lat.text = [NSString stringWithFormat:#"%.10f", LatitudeDouble];
}
My issue is when I run the app is updates the labels sometimes, but after a bit, its stops and when I close the app and reopen it the labels do not update at all.
What Am I doing wrong?
May be you should add this line self.locationManager.distanceFilter = 0.1
And fix your code like this
- (void)viewDidLoad
{
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
[locationManager requestWhenInUseAuthorization];
[locationManager requestAlwaysAuthorization];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = 0.1
[locationManager startUpdatingLocation];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
currentLocation = nil;
}
Try this
viewDidLoad:
locationManager =[[CLLocationManager alloc] init] ;
locationManager.delegate=self;
locationManager.desiredAccuracy=kCLLocationAccuracyBest;
[locationManager requestWhenInUseAuthorization];
[locationManager requestAlwaysAuthorization];
[locationManager startUpdatingLocation];
Info.plist:
NSLocationAlwaysUsageDescription
NSLocationWhenInUseUsageDescription
Then
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
NSLog(#"failed to update location");
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
CLLocation *currentLocation=[locations lastObject];
lat=currentLocation.coordinate.latitude;
lon=currentLocation.coordinate.longitude;
NSString *strLat=[NSString stringWithFormat:#"%f",lat];
NSString *strLon=[NSString stringWithFormat:#"%f",lon];
latitude_1=[[NSMutableString alloc] initWithString:strLat];
longitude_1=[[NSMutableString alloc] initWithString:strLon];
}

CLLocationCoordinate2D latitude & longitude always zero

I am trying to get latitude & longitude. I am running following code on actual device but I always get zero for latitude & longitude. I also import library and set delegate also. May I know what is wrong and how to do? My device has ios 8.
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
if ([locationManager locationServicesEnabled])
{
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
}
CLLocation *location = [locationManager location];
CLLocationCoordinate2D coordinate = [location coordinate];
NSString *str=[[NSString alloc] initWithFormat:#" latitude:%f longitude:%f",coordinate.latitude,coordinate.longitude];
NSLog(#"%#",str);
you have to get the current location in delegate method
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *currentLocation = [locations objectAtIndex:0];
}

CLLocationManager weird behavior

I have a weird problem.
I have 2 classes:
BusinessVC
FavoritesVC
In both of them i show the user the current distance from him to some specific point.
In both of the classes i use the EXACT same code for that.
FavoritesVC is presented as modal view controller.
For some reason didUpdateLocations / didUpdateToLocation methods are getting called ONLY in BusinessVC and NOT in FavoritesVC.
I'm implementing CLLocationManagerDelegate delegate in both classes.
The code I'm using:
-(void)viewDidLoad {
[super viewDidLoad];
[self locatedMe];
}
-(void) locatedMe{
NSLog(#"locateMe");
_locationManager = [[CLLocationManager alloc] init];
[_locationManager setDelegate:self];
[_locationManager setDistanceFilter:kCLDistanceFilterNone]; // whenever we move
[_locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters]; // 100 m
[_locationManager startUpdatingLocation];
}
// For iOS6
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation * newLocation = [locations lastObject];
NSNumber *lat = [[NSNumber alloc] initWithDouble:newLocation.coordinate.latitude];
NSNumber *lon = [[NSNumber alloc] initWithDouble:newLocation.coordinate.longitude];
self.userLocation = [[CLLocation alloc] initWithLatitude:[lat doubleValue] longitude:[lon doubleValue]];
}
// For earlier then iOS6
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
NSNumber *lat = [[NSNumber alloc] initWithDouble:newLocation.coordinate.latitude];
NSNumber *lon = [[NSNumber alloc] initWithDouble:newLocation.coordinate.longitude];
self.userLocation = [[CLLocation alloc] initWithLatitude:[lat doubleValue] longitude:[lon doubleValue]];
NSLog(#"%#",self.userLocation);
}
OK! Fixed that by running the code on main thread using this code:
-(void) locateMe {
NSLog(#"locateMe");
dispatch_async(dispatch_get_main_queue(), ^{
_locationManager = [[CLLocationManager alloc] init];
[_locationManager setDelegate:self];
[_locationManager setDesiredAccuracy:kCLLocationAccuracyBest]; // 100 m
[_locationManager startUpdatingLocation];
[_locationManager startUpdatingHeading];
});
}

trying to retrieve current location in iOS

I am building an app which requires me to find the distance between a location specified and my current location.
I am using CLLocationManager for the same but the coordinates retrieved are 0,0 despite me specifying a custom location in the simulator. Here's the code:
The .m file
#property (nonatomic, strong) CLLocationManager *locationManager2;
...
#synthesize locationManager2;
- (CLLocationManager *)locationManager2 {
if (locationManager2 != nil) {
return locationManager2;
}
locationManager2 = [[CLLocationManager alloc] init];
[locationManager2 setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
[locationManager2 setDelegate:self];
return locationManager2;
}
...
...
...
CLLocation *locationHome = [locationManager2 location];
NSLog(#"%f",locationHome.coordinate.latitude);
The lattitude is logged as zero.Anything wrong with my code?
Put this code and let me know what you are getting at console.
This code built on iOS 6.
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
if ([CLLocationManager locationServicesEnabled])
{
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
}
location = [locationManager location];
CLLocationCoordinate2D coordinate = [location coordinate];;
MKCoordinateRegion region;
region.center=coordinate;
MKCoordinateSpan span;
span.latitudeDelta=10.015;
span.longitudeDelta=10.015;
region.span=span;
[mapView setRegion:region];
NSString *str=[[NSString alloc] initWithFormat:#" latitude:%f longitude:%f",coordinate.latitude,coordinate.longitude];
NSLog(#"%#",str);

Resources