iOS CoreLocation not getting GPS coordinates - ios

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

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!

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];
}

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.

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);

Related

Local push notification by GPS position

I have a simple question about iOS, GPS Location and push notification.
Is possible in iOS to send a local push notification when the device is near of a specific GPS position?
Following code for ViewController.h file
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#interface ViewController : UIViewController <CLLocationManagerDelegate>{
CLLocationManager *locationManager;
NSString* lastNotification;
}
#end
Following code for ViewController.m file
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
lastNotification = #"";
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark -User Actions
- (IBAction)startLocaingMe:(id)sender{
[self startLocationReporting];
}
#pragma mark - Location Metods
- (void)startLocationReporting {
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;//or whatever class you have for managing location
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
[locationManager startUpdatingLocation];
}
// Delegate method from the CLLocationManagerDelegate protocol.
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
// If it's a relatively recent event, turn off updates to save power
CLLocation* location = [locations lastObject];
NSDate* eventDate = location.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
if (abs(howRecent) < 15.0) {
[self showNotificationIfDistanceIs100:location];
}
}
// this delegate method is called if an error occurs in locating your current location
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"locationManager:%# didFailWithError:%#", manager, error);
}
- (CLLocationDistance)distanceBetweenTwoPoints:(CLLocation*) location1 andSecond:(CLLocation*) location2{
CLLocationDistance distance = [location1 distanceFromLocation:location2];
return distance;
}
-(CLLocation*)House{
CLLocation *loc = [[CLLocation alloc] initWithLatitude:23.030064 longitude:72.546193];
return loc;
}
-(CLLocation*)passportOffice{
CLLocation *loc = [[CLLocation alloc] initWithLatitude:23.032034 longitude:72.549999];
return loc;
}
-(CLLocation*)ldCollageBusStand{
CLLocation *loc = [[CLLocation alloc] initWithLatitude:23.032515 longitude:72.549307];
return loc;
}
-(void)showNotificationIfDistanceIs100:(CLLocation*) location{
if ([self distanceBetweenTwoPoints:location andSecond:[self House]] <= 100) {
[self setLocalNotificaion:#"Your are 100 meter form House"];
}else if ([self distanceBetweenTwoPoints:location andSecond:[self passportOffice]] <= 100){
[self setLocalNotificaion:#"Your are 100 meter form Passport Office"];
}else if ([self distanceBetweenTwoPoints:location andSecond:[self ldCollageBusStand]] <= 100){
[self setLocalNotificaion:#"Your are 100 meter form Ld Collage Bus Stand"];
}
}
-(void)setLocalNotificaion:(NSString*)msg{
if ([lastNotification isEqualToString:msg] != YES) {
lastNotification = msg;
UILocalNotification *futureAlert;
futureAlert = [[UILocalNotification alloc] init];
[futureAlert setAlertBody:msg];
futureAlert.fireDate = [NSDate dateWithTimeIntervalSinceNow:0];
futureAlert.timeZone = [NSTimeZone defaultTimeZone];
[[UIApplication sharedApplication] scheduleLocalNotification:futureAlert];
}
}
#end
You can change location Long/Lati and getting the Localnotification
May this thinks lot helpful
-------EDITED---------
You can implement LocationManager instance and get notified about location updates in the following method:
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations {
// CLLocation object will be the content of the array locations
}
You can post UILocalNotification based on your requirements.

How to get current location using CLLocationManager in iOS

I can already find the current location using latitude and longitude, but I would also like to be able to find the current location given a zip code.
Here is what I have so far:
.h
#import <MapKit/MapKit.h>
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#interface ViewController : UIViewController<CLLocationManagerDelegate>
{
CLLocationManager *locationManager;
CLLocation *currentLocation;
IBOutlet UILabel *label1;
IBOutlet UILabel *lable2;
}
#property (weak, nonatomic) IBOutlet MKMapView *myMapview;
#property (weak, nonatomic) IBOutlet UILabel *label2;
#property (weak, nonatomic) IBOutlet UILabel *lable1;
#end
.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
locationManager = [[CLLocationManager alloc]init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
_myMapview.showsUserLocation = YES;
[self->locationManager startUpdatingLocation];
CLLocation *location = [locationManager 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);
NSLog(#"MY HOME :%#", latitude);
NSLog(#"MY HOME: %# ", longitude);
}
#pragma mark CLLocationManager Delegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
currentLocation = [locations objectAtIndex:0];
[locationManager stopUpdatingLocation];
[self->locationManager stopUpdatingLocation];
NSLog(#"my latitude :%f",currentLocation.coordinate.latitude);
NSLog(#"my longitude :%f",currentLocation.coordinate.longitude);
label1.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
lable2.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
NSLog(#"Detected Location : %f, %f", currentLocation.coordinate.latitude, currentLocation.coordinate.longitude);
CLGeocoder *geocoder = [[CLGeocoder alloc] init] ;
[geocoder reverseGeocodeLocation:currentLocation
completionHandler:^(NSArray *placemarks, NSError *error)
{
if (error)
{
NSLog(#"Geocode failed with error: %#", error);
return;
}
NSLog(#"Monday");
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(#"placemark.ISOcountryCode %#",placemark.ISOcountryCode);
}];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil)
{
label1.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
lable2.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Step 1: Import MobileCoreServices framework in .h File
#import <MobileCoreServices/MobileCoreServices.h>
Step 2: Add delegate CLLocationManagerDelegate
#interface yourViewController : UIViewController<CLLocationManagerDelegate>
{
CLLocationManager *locationManager;
CLLocation *currentLocation;
}
Step 3: Add this code in class file
- (void)viewDidLoad
{
[super viewDidLoad];
[self CurrentLocationIdentifier]; // call this method
}
Step 4: Method to get location
//------------ Current Location Address-----
-(void)CurrentLocationIdentifier
{
//---- For getting current gps location
locationManager = [CLLocationManager new];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
//------
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
currentLocation = [locations objectAtIndex:0];
[locationManager stopUpdatingLocation];
CLGeocoder *geocoder = [[CLGeocoder alloc] init] ;
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error)
{
if (!(error))
{
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(#"\nCurrent Location Detected\n");
NSLog(#"placemark %#",placemark);
NSString *locatedAt = [[placemark.addressDictionary valueForKey:#"FormattedAddressLines"] componentsJoinedByString:#", "];
NSString *Address = [[NSString alloc]initWithString:locatedAt];
NSString *Area = [[NSString alloc]initWithString:placemark.locality];
NSString *Country = [[NSString alloc]initWithString:placemark.country];
NSString *CountryArea = [NSString stringWithFormat:#"%#, %#", Area,Country];
NSLog(#"%#",CountryArea);
}
else
{
NSLog(#"Geocode failed with error %#", error);
NSLog(#"\nCurrent Location Not Detected\n");
//return;
CountryArea = NULL;
}
/*---- For more results
placemark.region);
placemark.country);
placemark.locality);
placemark.name);
placemark.ocean);
placemark.postalCode);
placemark.subLocality);
placemark.location);
------*/
}];
}
Here is a code to get user current location using block
1) #import <CoreLocation/CoreLocation.h>
2) <CLLocationManagerDelegate>
3) in .h file
//Location
typedef void(^locationBlock)();
//Location
-(void)GetCurrentLocation_WithBlock:(void(^)())block;
#property (nonatomic, strong) locationBlock _locationBlock;
#property (nonatomic,copy)CLLocationManager *locationManager;
#property (nonatomic)CLLocationCoordinate2D coordinate;
#property (nonatomic,strong) NSString *current_Lat;
#property (nonatomic,strong) NSString *current_Long;
4) in .m file
#pragma mark - CLLocationManager
-(void)GetCurrentLocation_WithBlock:(void(^)())block {
self._locationBlock = block;
_locationManager = [[CLLocationManager alloc] init];
[_locationManager setDelegate:self];
[_locationManager setDistanceFilter:kCLDistanceFilterNone];
[_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
if (IS_OS_8_OR_LATER) {
if ([_locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]) {
[_locationManager requestWhenInUseAuthorization];
[_locationManager requestAlwaysAuthorization];
}
}
[_locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation *currentLoc=[locations objectAtIndex:0];
_coordinate=currentLoc.coordinate;
_current_Lat = [NSString stringWithFormat:#"%f",currentLoc.coordinate.latitude];
_current_Long = [NSString stringWithFormat:#"%f",currentLoc.coordinate.longitude];
NSLog(#"here lat %# and here long %#",_current_Lat,_current_Long);
self._locationBlock();
[_locationManager stopUpdatingLocation];
_locationManager = nil;
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error {
}
5) Call function
- (void)viewDidLoad {
[super viewDidLoad];
[self GetCurrentLocation_WithBlock:^{
NSLog(#"Lat ::%f,Long ::%f",[self.current_Lat floatValue],[self.current_Long floatValue]);
}];
}
6) And add below line to .plist
Any one or both of below keys needs to be added in Info.plist file.
NSLocationWhenInUseUsageDescription
NSLocationAlwaysUsageDescription
if location permissions not asking when you first launch then you cant get your current location .
iOS8 has got us major API changes with the LocationsServices
Assuming [CLLocationManager locationServicesEnabled] return YES,
With the First Launch of the iOS App [both iOS7 and iOS8] - locationMangers(CLLocationManager)
You can call Google APIs Maps service to get the location using zipcode:
Just enter your zipcode in address={your zipcode}.

Unable to store user's location in a variable

- (IBAction)getdirections:(id)sender {
directionview=[[directionViewController alloc]initWithNibName:#"directionViewController" bundle:nil];
directionview.sourceplace=user.location;
[self.view addSubview:directionview.view];
}
I want to store the user's locations in "sourceplace" which is a NSString type variable in another view controller named "directionViewController".
I am fetching data in variable "user" from and i tried NSLogging user and i can see that it has the "location" key.
In your .h :
#import <CoreLocation/CoreLocation.h>
#interface yourController : UIViewController <CLLocationManagerDelegate> {
CLLocationManager *locationManager;
NSString *str;
}
In your .m :
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
You can convert location to string from location like this:
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation *location = [locations lastObject];
str=[[NSString alloc] initWithFormat:#" latitude:%f longitude:%f", location.coordinate.latitude, location.coordinate.longitude];
NSLog(#"%#",str);
}
after
if your directionview.sourceplace is a NSString too:
directionview.sourceplace = str;

UIlabel doesn't update user current speed

been having this problem for a few days now and can't seem to find a solution for it. It's probably some very basic stuff but still can't come up with a solution. So I'm trying to have my uilabel update a user speed in a car or on bike. But When the UIlabel update, it doesn't update the correct value. Any help will be appreciated.
Heres my .h file
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#interface MainViewController : UIViewController <LoginDelegate,WEPopoverParentView,PopoverControllerDelegate,MainMenuDelegate,MKMapViewDelegate,UIActionSheetDelegate,UIAccelerometerDelegate, CLLocationManagerDelegate, NSObject>
{
AppDelegate *appDelegate;
IBOutlet MKMapView *userMap;
CLLocationManager *locationManager;
}
#property (strong, nonatomic) IBOutlet UILabel *speedView;
#property(nonatomic) int speedCount;
#property (nonatomic,retain) CLLocationManager *locationManager;
#property (nonatomic, strong) WEPopoverController *popoverController;
+ (NSString *) speedToMPH: (float) value;
- (IBAction)btnMenuTapped:(id)sender;
#end
and my .h file
#implementation MainViewController
#synthesize speedCount;
#synthesize speedView;
#synthesize popoverController;
#synthesize locationManager;
- (void)locationError:(NSError *)error {
speedView.text = [error description];
}
-(void)viewWillAppear:(BOOL)animated
{
[userMap setRegion:MKCoordinateRegionMakeWithDistance(userMap.userLocation.coordinate, 5, 5) animated:YES];
}
- (void)viewDidLoad
{
[super viewDidLoad];
appDelegate = [[UIApplication sharedApplication] delegate];
locationManager =[[CLLocationManager alloc] init];
// Do any additional setup after loading the view, typically from a nib.
[userMap setCenterCoordinate: userMap.userLocation.coordinate animated: YES];
[self performSelector:#selector(checkForLogin) withObject:nil afterDelay:1];
[self startLocationServices];
// create LM
self.locationManager = [CLLocationManager new];
// set its delegate
[self.locationManager setDelegate:self];
// set configuration
[self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[self.locationManager setDistanceFilter:kCLDistanceFilterNone];
// start location services
[self.locationManager startUpdatingLocation];
// create an oldLocation variable if one doesn't exist
}
- (void)startLocationServices
{
// create the Location Manager
if (self.locationManager == nil) {
self.locationManager = [CLLocationManager new];
}
// stop services
[self.locationManager stopUpdatingLocation];
[self.locationManager setDelegate:nil];
self.speedView.text = #"Location Services stopped.";
}
// locationManager didUpdateToLocation FromLocation
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
NSLog(#"%#", newLocation);
self.speedView.text = [NSString stringWithFormat:#"%d %.f ", speedCount, [newLocation speed]];
}
+ (NSString *) speedToMPH: (float) value
{
NSString *speedCount = #"0.0 ";
if (value>0) {
float mile = 1609.344f;
float mph = value / mile * 3600;
speedCount = [NSString stringWithFormat: #"%.f ", mph];
}
return speedCount;
}
CLLocation returns the speed in meters per second. So you will have to convert it to miles per hour by multiplying the value with 2.23694.
self.speedView.text = [NSString stringWithFormat:#"%d %.f ", speedCount, [newLocation speed] * 2.23694];

Trying to get current location, but LocationManager delegate never get called

here is my code, i am trying to get my current longtitude and latitude,
so my location will be display on map view.
however, the location manager delegate never get called, so i always getting longitude = 0.0000 and latitude = 0.0000.....
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#interface MapViewController : UIViewController <CLLocationManagerDelegate>
#property (weak, nonatomic) IBOutlet MKMapView *mapView;
#property(retain,nonatomic)CLLocationManager *locationManager;
#property(assign,nonatomic)float longitude;
#property(assign,nonatomic)float latitude;
#end
and this is the implementation file:
#import "MapViewController.h"
#define METERS_PER_MILE 1609.344
#interface MapViewController ()
#end
#implementation MapViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.locationManager = [[CLLocationManager alloc] init];
[self getCurrentLocation];
CLLocationCoordinate2D zoomLocation;
zoomLocation.latitude = self.latitude;
zoomLocation.longitude = self.longitude;
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, 0.5*METERS_PER_MILE, 0.5*METERS_PER_MILE);
[self.mapView setRegion:viewRegion animated:YES];
NSLog(#"longitu
de %f", self.longitude);
NSLog(#"latitude %f", self.latitude);
}
-(void)getCurrentLocation
{
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[self.locationManager startUpdatingLocation];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)viewDidUnload {
[self setMapView:nil];
[super viewDidUnload];
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", error);
UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Failed to get your location" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
NSLog(#"didUpdateToLocation: %#", [locations lastObject]);
CLLocation *currentLocation = [locations lastObject];
if (currentLocation != nil) {
self.longitude = currentLocation.coordinate.longitude;
self.latitude = currentLocation.coordinate.latitude;
NSLog(#"cal longitude %f", self.longitude);
NSLog(#"cal latitude %f", self.latitude);
}
}
#end
can anyone give me some advise please. cheers
May be you are running the code on simulator and SDK is below 6.0. In this case you get only 0.0000 as latitude and longitude. And make sure that application is granted access to device location.
If you just want to get current location then do the following :
-(void)getCurrentLocation
{
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[self.locationManager startUpdatingLocation];
CLLocation currentLocation = self.locationManager.location;
[self.locationManager stopUpdatingLocation];
}
BTW, never use self when initialize any object. Because doing this creates 2 object.
first object is created by right side of this line self.locationManager = [[CLLocationManager alloc] init];. Second object is created when setter method is called by left side of the same line, to assign an object to locationManager variable.

Resources