IOS how to get live latitude and longitude - ios

I want the current latitude and longitude of my device. I can print latitude and longitude when my program locate the device for the first time but I can't refresh it.
-(void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
int lastindex = [locations count]-1;
CLLocation * currentLocation = [locations objectAtIndex:lastindex];
float latitude =currentLocation.coordinate.latitude;
float longitude =currentLocation.coordinate.longitude;
NSLog(#"LAT:%f LONG:%f",latitude,longitude);
[self latitudeLabel].text = [[NSString alloc]initWithFormat:#"latitude : %#",[[NSNumber numberWithFloat:latitude] stringValue]];
[self longitudeLabel].text = [[NSString alloc]initWithFormat:#"longitude : %#",[[NSNumber numberWithFloat:longitude] stringValue]];
}
This is what I tried but latitude/longitude are never updated. I tried it with the function didUpdateHeading but that didn't work either.
How can i do this. Any one can help me to solve this issue.
Thanks you

This method is triggered by startUpdatingLocation which I assume you're using since it did get called at least once. The method gets called each time the location data changes. Is your location actually changing enough to trigger it? Also, check the distanceFilter property on your CLLocationManager and make sure it is low enough.

Make sure you add the following to your header:
#interface YourLocationObject : SomeObject <CLLocationManagerDelegate>
.. and when you create your CLLocationManager object, you set yourself as the delegate:
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
//... other customization here ...//
[locationManager startUpdatingLocations];

Related

iPhone Getting the wrong coordinates from the GPS

IOS10 on iPhone 6 Plus.
A small app app that grabs the gps coordinates and sends them to a remote web service. On the iphone map the user location is showing correctly, but the retrieved coordinates:
location.coordinate.latitude,
location.coordinate.longitude
are 0.5 miles away from where the map says I am! This is consistent wherever I move to.
I am following Apple's best practices and using the delegate method as follows: and it's these coordinates that are incorrect.
// Delegate method from the CLLocationManagerDelegate protocol.
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations {
CLLocation* location = [locations lastObject];
NSDate* eventDate = location.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
if (abs(howRecent) < 15.0) {
// Log the data
NSLog(#"latitude %+.6f, longitude %+.6f\n",
location.coordinate.latitude,
location.coordinate.longitude);
}
}
I am setting the location accuracy as follows:
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
I sample the gps coordinates for 30 seconds to make sure i am getting the best accuracy possible.
I have tried this on 2 different iPhones, both showing the same issue.
Thanks in advance.
I finally found out what is causing the problem..
I am currently in China... and that is the reason for the mysterious offset.. the maps in China are 'offset'.
If you are interested there's an post about it here that has saved me from tearing my hair out.
http://www.sinosplice.com/life/archives/2013/07/16/a-more-complete-ios-solution-to-the-china-gps-offset-problem.
China uses a mapping projection called GCJ-02 which is different from the West's mapping standard (WGS-84). So if you're ever developing a mapping system, you might want to take this into account for travellers in China!
Thanks anyway for the useful pieces of coding advice.
You can add a check in your method to update locations again until you are down to your desired accuracy:
// Delegate method from the CLLocationManagerDelegate protocol.
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations {
// You can check for either locationManager.desiredAccuracy or a value you'd like in meters
CLLocation* location = [locations lastObject];
if (location.horizontalAccuracy > locationManager.desiredAccuracy) {
//Do nothing yet
return;
}
NSDate* eventDate = location.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
if (abs(howRecent) < 15.0) {
// Log the data
NSLog(#"latitude %+.6f, longitude %+.6f\n",
location.coordinate.latitude,
location.coordinate.longitude);
}
}

Get User Final Location IOS

I'm doing a query inside of:
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
if (!gotLocation){
gotLocation = true;
[locationManager stopUpdatingLocation];
// DO QUERY
}
}
But I would like to know when the final location is set, or when a more accurate one is made. I'm trying to query only once and need a precise location for the query. I know I can use [locations lastObject], but how can I determine when the final or a more precise location is set.
You can check the location's horizontalAccuracy. The smaller the value the more accurate. You should hold a reference to the last location you received then when a new location comes in that is more accurate, the horizontalAccuracy is smaller, updated your reference.
Then once you receive a location with a horizontalAccuracy close enough for your use case then you can call stopUpdatingLocation since you have your location, then do your query.
For example:
CLLocation *location = [locations lastObject];
if (location.horizontalAccuracy < self.lastLocation.horizontalAccuracy) {
self.lastLocation = location;
if (self.lastLocation.horizontalAccuracy <= kDesiredLocationAccuracy) {
// execute query or additional logic
[locationManager stopUpdatingLocation];
}
}
Hope that helps!

Core Location can't get data in viewDidLoad

I wrote a simple iOS application that retrieves location information and then uses the location to request Yahoo Weather.
The problem is that even when I call the Core Location in the viewDidLoad, it won't give me the result immediately.
So why can't I get the location information?
How can I get the location information in viewDidLoad?
The pseudocode currently is something like:
- (void)viewDidLoad
{
[super viewDidLoad];
self.locManager = [[CLLocationManager alloc] init];
self.locManager.delegate = self;
self.locManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locManager.distanceFilter = 100;
[self.locManager startUpdatingLocation];
//won't get the current location right now, so the output will be null
NSLog(#"Current Location Longitude: %#", self.longitudeString);
NSLog(#"Current Location Latitude: %#", self.latitudeString);
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *newLocation = [locations lastObject];
self.longitudeString = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
self.latitudeString = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
}
Location updates are not provided as instantly as you are expecting, you need to wait few seconds (2-3 or may be more) to get precise location update. If you want to have location data in viewDidLoad then you should init your location manager (and call startUpdatingLocation) before invoking the ViewController (since then it is not guaranteed that you will have location-data in viewDidLoad).

Altitude is always zero on iPhone simulator

I'm trying to develop an Altimeter on Xcode and Simulator but it always return 0 for the height above the sea.
I don't understand why, I've tried with a lot of places on Simulator.
My code is this:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
_mapView.delegate = self;
_locationManager = [[CLLocationManager alloc] init];
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
_locationManager.pausesLocationUpdatesAutomatically = YES;
_locationManager.delegate = self;
firstLocation = YES;
checkUserLocation = NO;
}
- (void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
CLLocation *location = [locations lastObject];
lastLocation = location.coordinate;
_latitudeLabel.text = [NSString stringWithFormat:#"Current latitude: %f", location.coordinate.latitude];
_longitudeLabel.text = [NSString stringWithFormat:#"Current longitude: %f", location.coordinate.longitude];
_altitudeLabel.text = [NSString stringWithFormat:#"Current altitude: %f m", location.altitude];
}
Where is my error?
There's nothing wrong with your code, its because you are using the simulator.
Determining altitude requires a device with GPS capabilities, and you also need to be using GPS on that device in order to get it (wifi only location would not report altitude correctly even on GPS-enabled devices). The iOS simulator does not have those capabilities so altitude will not be accurate there. You will need to use a real device with GPS to get altitude measurements.
If you want to simulate a CLLocation with altitude you can create your CLLocation object and pass it an altitude yourself:
- (id)initWithCoordinate:(CLLocationCoordinate2D)coordinate
altitude:(CLLocationDistance)altitude
horizontalAccuracy:(CLLocationAccuracy)hAccuracy
verticalAccuracy:(CLLocationAccuracy)vAccuracy
timestamp:(NSDate *)timestamp
Altitude is a readonly property so you will need to create a new CLLocation object yourself instead of changing it manually when you receive a CLLocation object in your delegate callback.

Application crashes when requesting CLLocation property from appDelegate

I have an application which creates a class instance that contains (amongst other things) some location data.
In the app delegate I set up location services and start grabbing the location data;
//Delegate method to receive location information from locationManager
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
latestLocation = newLocation;//Make latest location the same as NewLocation
NSLog(#"Location is: %#", latestLocation);
}
I declare latest location as a property so that I can get at the CLLocation instance from another class.
My captures class, when called grabs the CLLocation when its init method is called;
//Designated initialiser
-(id) initWithVideoPath:(NSString *) vPath
userNotes:(NSString *) uNotes
retentionState:(NSString *) rState
{
//Call the super classes designated initializer
[super init];
//Get a pointer to the application delegate so we can access the location props
Rolling_VideoAppDelegate *appDelegate = (Rolling_VideoAppDelegate*)[UIApplication sharedApplication].delegate;
//If superclass failed to init
if (!self)
return nil;
//Give the variables some initial values
[self setVideoPath:vPath];
[self setUserNotes:uNotes];
[self setRetentionState:rState];
dateCreated = [[NSDate alloc] init];
mp = [[MapPoint alloc]initWithCoordinate:[[appDelegate latestLocation]coordinate]];//get the location from the coords from appDelegate
return self;
[dateCreated release];
}
However the app crashes when the mapPoint init is called. The problem is I'm not getting the CLLocation information in properly.
I'm still unsure why the original solution does not work, so if anyone has any insights please do enlighten.
I have however worked out a slightly inelegant work around using NSUserDefaults
latestLocation = newLocation;//Make latest location the same as NewLocation
//Use NSUser Defaults to save the CLLocation instance
NSUserDefaults *location = [NSUserDefaults standardUserDefaults];
[location setDouble:latestLocation.coordinate.latitude forKey:#"lat"];
[location setDouble:latestLocation.coordinate.longitude forKey:#"longd"];
I needed to break out the lat and long as NSUserDefaults will not store CLLocation objects (NSCoding compatability), the reconstruct them in the captures class;
NSUserDefaults *location = [NSUserDefaults standardUserDefaults];//Get a handle to the user defaults
CLLocationDegrees lat = [location doubleForKey:#"lat"];
CLLocationDegrees longd = [location doubleForKey:#"longd"];
CLLocation *currentLocation = [[CLLocation alloc] initWithLatitude:lat longitude:longd];
mp = [[MapPoint alloc]initWithCoordinate:[currentLocation coordinate]];//get the location from the coords from appDelegate

Resources