I have a CLLocation manager called "myLocation".
myLocation = [[CLLocationManager alloc] init];
myLocation.desiredAccuracy = kCLLocationAccuracyBestForNavigation ;
myLocation.distanceFilter = 10 ;
myLocation.delegate=self;
locationEnabledBool = [CLLocationManager locationServicesEnabled];
if (locationEnabledBool ==NO || ( [CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied)) {
// LocationText.text = #"Location Service Disabled ";
UIAlertView *locationAlert = [[UIAlertView alloc] initWithTitle:#"Location Service Disabled"
message:#"To re-enable, please go to Settings and turn on Location Service for this app."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[locationAlert show];
[locationAlert release];
}
[myLocation startUpdatingLocation];
and location update function is
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
NSLog(#"old location is %f, %f ", oldLocation.coordinate.latitude, oldLocation.coordinate.longitude);
NSLog(#"new location is %f,%f",newLocation.coordinate.latitude, newLocation.coordinate.longitude );
}
Is there a way to find frequency of location manager update, and If it can be increased or decreased?
Your location update starts only when you call the method [locationManager startUpdatingLocation].
You can control the frequency of the update using an NSTimer. Call the startUpdatingLocation method at regular intervals whenever you need a location update and then immediately call the stopUpdatingLocation method. The next time you will get a location update only at the interval you have set in the NSTimer.
For detecting even the slightest of movements, you need to set
myLocation.distanceFilter = kCLDistanceFilterNone ;
But, please keep in mind,letting location manager to generate updates for even the slightest of movements can end up in lot of battery usage.
Related
I need to get user location and fetch latitude and longitude of even when there is no internet available.
Right now i have implemented CoreLocation methods:-
-(void)updatestart
{
// Current location
_locationManager = [[CLLocationManager alloc]init];
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
_locationManager.delegate = self;
[_locationManager startUpdatingLocation];
}
- (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
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation{
[_locationManager stopUpdatingLocation];
NSLog(#"%f",_locationManager.location.coordinate.latitude);
NSLog(#"%f",_locationManager.location.coordinate.longitude);
}
and i am getting the location updates but this only works if we have internet connection.
I guess using iPhone GPS we can fetch the location even without internet.
Any idea of how to implement that??
Thanks in advance.
GPS doesn't need data exchange using internet, but it has basically 2 disadvantages:
it takes a long time to get position if you haven't used it recently (this is
due to satellite search)
it doesn't work inside buildings or where streets are too small
between buildings (this happens a lot in Italy)
Another way that it doesn't need data exchange is location based on cell tower, but of course your device should have cellular chip installed.
From your code I see three things that should be fixed as soon as possible.
Sometimes the first location is cached and it doesn't represent the
actual location
It will be better to stop the location manager when you receive a
valid coordinate, that means: not cached, with an horizontal accuracy >=0 and with an horizontal accuracy that match your requirements,
The delegate methods to get location is deprecated (depending on your
deployment target). Here is a little snippet for the first two
points:
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
CLLocation * newLocation = [locations lastObject];
if (newLocation.horizontalAccuracy < 0) {
return;
}
NSTimeInterval interval = [newLocation.timestamp timeIntervalSinceNow];
if (abs(interval)>20) {
return;
}
}
I am trying to make an app in which the view will check whether the location services are enabled or not . If it is not enabled then it will prompt one with a pop up but still it will keep on searching for location but not prompt. As soon as the location services are enabled it will continue its process.
How to do that???
You cannot continue getting the location if location service are disabled.
If you want to continue searching for location be sure that the service is enable by checking
[CLLocationManager locationServicesEnabled]
If enabled, start updating the location
[locationManager startUpdatingLocation];
Then in
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
[locationManager stopUpdatingLocation]; // This will stop to check the location
}
remove this code to still check the location [locationManager stopUpdatingLocation];, but this is not the best approach, be sure to read the apple documentation for the policy of getting the location
You can check location services availability through this code :
MKUserLocation *userLocation = map.userLocation;
BOOL locationAllowed = [CLLocationManager locationServicesEnabled];
BOOL locationAvailable = userLocation.location!=nil;
if (locationAllowed==NO) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Location Service Disabled"
message:#"To re-enable, please go to Settings and turn on Location Service for this app."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
} else {
if (locationAvailable==NO)
[self.map.userLocation addObserver:self forKeyPath:#"location" options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld) context:nil];
}
Add in .h file int counter;
In your view's viewDidLoad method add this as it will check for every second u can increase counter:
[NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:#selector(checkLocationMangerEnabled:)
userInfo:nil
repeats:YES];
counter = 0;
Now selector would be:
-(void)checkLocationMangerEnabled:(id)sender
{
if([CLLocationManager locationServicesEnabled])
{
//here location is enabled
}
else
{ //Not enabled
if(counter == 60) // alert will showed in every 1 min u can increase or decrese
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Location Service Disabled"
message:#"To re-enable, please go to Settings and turn on Location Service for this app."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
counter++;
}
}
I want to get the user's current location from my iPhone app. I want to show the user's current location like country name, latitude, longitude information in my app. And also i want to show the location in Google map also. I have tried Google search also, but can't get the exact answer. I have get the info that was to use CLLocationManager in my app to track the location. How do i use this? I have download one sample app from Apple Documents. Here is the link: https://developer.apple.com/library/ios/#samplecode/LocateMe/Introduction/Intro.html
Can you please help me on this? Thanks in advance.
1) I have get the info that was to use CLLocationManager in my app to track the location. How do i use this?
in .h file
#include <CoreLocation/CLLocationManagerDelegate.h>
#include <CoreLocation/CLError.h>
#include <CoreLocation/CLLocation.h>
#include <CoreLocation/CLLocationManager.h>
CLLocationManager * myLocationManager;
CLLocation * myLocation;
in .m file :-
-(void)findMyCurrentLocation
{
self.myLocationManager = [[[CLLocationManager alloc] init] autorelease];
[[self myLocationManager] setDelegate:self ];
[myLocationManager startUpdatingLocation];
double latitude=34.052234;
double longitude=-118.243685;
CLLocation *defaultLocation =[[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
[self setMyLocation:defaultLocation];
[defaultLocation release];
if( [CLLocationManager locationServicesEnabled] )
{
NSLog(#"Location Services Enabled....");
locationServicesEnabled=TRUE;
UIAlertView *alert = [ [UIAlertView alloc] initWithTitle:#"Information"
message:#"Fetching your current location."
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil ];
[alert release];
}
else
{
NSLog( #"Location Services Are Not Enabled...." );
locationServicesEnabled=FALSE;
UIAlertView *alert = [ [UIAlertView alloc] initWithTitle:#"Information"
message:#"Location service is not enable. Please enable it from settings."
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil ];
[alert release];
}
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation: (CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
[self setMyLocation:newLocation];
NSString *tempLat = [ NSString stringWithFormat:#"%3.6f" , (newLocation.coordinate.latitude) ];
NSString *tempLong= [ NSString stringWithFormat:#"%3.6f" , (newLocation.coordinate.longitude)];
appDelegate.curlat = tempLat;
appDelegate.curlong = tempLong;
}
- (void)locationManager: (CLLocationManager *)manager didFailWithError: (NSError *)error
{
printf("\nerror");
UIAlertView *alert = [ [UIAlertView alloc] initWithTitle:#"Error"
message:#"Error while getting your current location."
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil ];
[alert release];
}
2). I want to show the user's current location like country name information in my app.
For this you can to use Google's Reverse Geo coding OR MKReverseGeocoder
this should do most of it..
http://www.highoncoding.com/Articles/804_Introduction_to_MapKit_Framework_for_iPhone_Development.aspx
to get the information on the location you need to use MKReverseGeocoder
https://developer.apple.com/library/ios/#documentation/MapKit/Reference/MKReverseGeocoder_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40008323
First create an instance of the MKMapView
To get user's latitude and longitude:
In your viewDidLoad
[yourMapView setShowsUserLocation:YES];
CLLocationCoordinate2D userCoord;
userCoord.latitude=map_view.userLocation.coordinate.latitude;
userCoord.longitude=map_view.userLocation.coordinate.longitude;
//NSLogging these on simulator will give you Cupertino or whatever location you set in location simulation.
And for country name you will need reversegeocoding you can look at the class reference here
https://developer.apple.com/library/ios/#documentation/MapKit/Reference/MKReverseGeocoder_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40008323
OR
If MKReverseGeoCoding gets too complicated you can use Yahoo's reversegeocoder
http://where.yahooapis.com/geocode?q=%f,%f&gflags=R&appid=yourAppId, those 2 %f will be userCoord.longitude and userCoord.latitude.
Yes you can use CLGeoCoder. But CLGeaCoder will not provide accrurate location inforamtion outside of USA for other country like India etc. So better to use Google's Reverse Geo coding SVGeoCoder. SVGeoCoder have nice implementation to get location with goolePlaceAPI.
I want to show user's current location with iphone gps feature but problem is it is giving incorrect location .
When i drop pin on map then it drops pin at exact position but when i try to see the location in text then it gives inaccurate location with inaccuracy of 500 to 800 meters approx.I have used reverse geocoding and google api but all giving same location. PLease tell me why this happens and how can i show the exact location of user ?
My code is:
cllocationmanager *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyBest; // 100 m
[locationManager startUpdatingLocation];
}
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
CLLocationCoordinate2D here = newLocation.coordinate;
NSLog(#"%f %f ", here.latitude, here.longitude);
MKReverseGeocoder *geocoder = [[MKReverseGeocoder alloc] initWithCoordinate:here];
[geocoder setDelegate:self];
[geocoder start];
}
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error{
}
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark
{
NSLog(#"The geocoder has returned: %#", [placemark addressDictionary]);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error" message:[NSString stringWithFormat:#"%#",[placemark addressDictionary]] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
[alertView release];
}
Quick guess: did you check the CLLocation's horizontal accuracy? Quite often the first response I get is very inaccurate, and then subsequent calls get better.
Edit: #pankaj First of all, can you confirm that it is an accuracy issue. If it is the problem that I'm suggesting, then the CLLocation horizontalAccuracy will be large. If not the case then you can ignore my answer and these comments. However, if horizontalAccuracy is a large error then you will have to wait for a better lock. There are two ways to do this:
Wait for a short period of time (a second or two) and see if you get a better lock.
Start requesting location much earlier on, e.g. when the app launches, or when the UIViewController that requires location starts.
This is my first question in this site.
I have this serious problem.... I'll explain this from the beginning…
in my app i need to get the current location of the user when the user click on the button in the application.. but the problem is when is click on the button its not updating to the current location its getting the previous location. But when i reset the location warnings in the iphone app its get the correct location.
Here is the code steps i did for this application to get the current location of the user...
First I import to the application ...
then i am using global files to keep data of the application because i need to access them through the application.
so what I did in the globle.m and .h file is ...
CLLocationManager* locationManager;
#synthesize locationManager
+ (Globals*)sharedGlobals {
#synchronized(self) {
if(_sharedGlobals == nil) {
_sharedGlobals = [[super allocWithZone:NULL] init];
_sharedGlobals.locationManager = [[CLLocationManager alloc]init];
[_sharedGlobals.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
}
}
return _sharedGlobals;
}
Then in my other view controller I put the CLLocationManagerDelegate and in the .m file
-(IBAction) didTapSearchbtn{
if (![CLLocationManager locationServicesEnabled]) {
}else {
[[Globals sharedGlobals].geoLocations removeAllObjects];
search.text = nil;
[Globals sharedGlobals].fromTextField = NO;
[[Globals sharedGlobals].locationManager setDelegate:self];
[[Globals sharedGlobals].locationManager startUpdatingLocation];
}
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
if (newLocation.horizontalAccuracy < 0) return;
[[Globals sharedGlobals].locationManager setDelegate:nil];
[[Globals sharedGlobals].locationManager stopUpdatingLocation];
[[Globals sharedGlobals].geoLocations setObject:[[NSString alloc] initWithFormat:#"%f", newLocation.coordinate.latitude] forKey:#"geolat"];
[[Globals sharedGlobals].geoLocations setObject:[[NSString alloc] initWithFormat:#"%f", newLocation.coordinate.longitude] forKey:#"geolong"];
[self retriveDataFromInternet];
[[Globals sharedGlobals].locationManager release];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
//GPS error
[[Globals sharedGlobals].locationManager setDelegate:nil];
[[Globals sharedGlobals].locationManager stopUpdatingLocation];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"YumTable!", nil) message:NSLocalizedString(#"Enable Your GPS settings to get your current location", nil) delegate:nil cancelButtonTitle:NSLocalizedString(#"Ok", nil) otherButtonTitles:nil];
[alert show];
[alert release];
[[Globals sharedGlobals].locationManager release];
}
i put the label to my view controller and went different places to take latitudes and longitudes .. but always it getting same latitude and longitude ... but when I reset the location warnings and run the app again it took the correct latitude and longitude ... so if i need to take current location always i have to reset it. But what i need is to get current location every time when i click the search button...
Can any one can say whats wrong in this code and can any one help me ....
And Also very very sorry about my bad english ... :)
The LocationManager will return the previos location because it tries to be as fast as possible and it thinks that this location might be good enough. I usually check the timestamp on the new location to ensure that it is a fresh one. If it is to old I don't stop the manager and wait for the next one.
I would suggest that you look at the sample code provided by Apple, https://developer.apple.com/library/ios/#samplecode/LocateMe/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007801
This code is copied from the example:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
// test the age of the location measurement to determine if the measurement is cached
// in most cases you will not want to rely on cached measurements
NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
if (locationAge > 5.0) return;
}
I missed Typed my code ... after I figur that out my application start to work perfectly ... Thank you guys for your great help..
[_sharedGlobals.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
instead of that I used
[_sharedGlobals.locationManager setDesiredAccuracy:kCLLocationAccuracyBestforNavigation];