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);
Related
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.
I have an iOS app that uses a users current location to show directions/ distance between the users current location and a destination point. I am able to show the destination point on the map, however when I try to get the user's current location using CLlocationManager, it returns coordinates (0,0). Below is my code for retrieving the users location.
Is retrieving current location possible on the Apple Watch?
If so, what am I doing wrong here that the location is returning (0,0)?
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
locationManager.distanceFilter = 5;
CLLocation *location = locationManager.location;
CLLocationCoordinate2D myLoc = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude);
Also, I have #import < CoreLocation/CoreLocation.h> in my .h file and < CLLocationManagerDelegate>
Try the following code:
#property (nonatomic, strong) CLLocationManager *locationManager;
- (void)willActivate
{
self.locationManager = [[CLLocationManager alloc] init];
[self.locationManager setDelegate:self];
[self.locationManager requestLocation];
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations
{
if ([locations count] == 0) {
// error
return;
}
// success
self.currentLocation = [locations firstObject];
CLLocationCoordinate2D myLoc = CLLocationCoordinate2DMake(
self.currentLocation.coordinate.latitude,
self.currentLocation.coordinate.longitude);
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(nonnull NSError *)error
{
// error
}
If you did not implemented this:
(with attributes inspector or programmatically)
self.mapView.showsUserLocation = YES
Or in addition to tell the mapView that the user's location is depending of LocationManager.location
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];
}
I want to receive in coordinates the users current location and I entered this code:
-(void)update{
locationManager = [[CLLocationManager alloc] init];
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.delegate = self;
mapView.showsUserLocation = YES;
[locationManager startUpdatingLocation];
}
On iOS Simulator, this code is crashing and on my device it is not or sometimes its crashes the whole app.... can you help me on what is going on?
It looks like maybe you're not implementing the CLLocationManagerDelegate methods.
In particular -locationManager:didUpdateLocations: (from iOS 6) or -locationManager:didUpdateToLocation:fromLocation: in previous iOS versions.
Maybe (again your question is so vague) you only want to show the blue dot on a map view. In which case you don't need to deal with the Core Location Manager. Check out this post for more information.
1st of all You can't get your current Location in the Simulator . and try with this code for getting the co-ordinates of current Location.
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);
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];
}