Settings default value to float variable - objective-c

I'm developing a location based app and I'm using the following code (which works perfectly) to retrieve the location of the user. However, I would like to set a default value to the longitude and latitude in case the user turned off location services.
I tried self.latitude = 0; but the app crashes. latitude and longitude are variables of type float. Ideally I want to set them to a default value of (0,0).
So basically: how can I set a default value for a variable of type float?
Thanks for your help.
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
self.latitude = newLocation.coordinate.latitude;
self.longitude = newLocation.coordinate.longitude;
SVGeocoder *geocodeRequest = [[SVGeocoder alloc] initWithCoordinate:newLocation.coordinate];
[geocodeRequest setDelegate:self];
[geocodeRequest startAsynchronous];
// NSLog(#"lat:%f,long:%f",self.latitude,self.longitude);
[self.locationMgr stopUpdatingLocation];
}

Related

CLLocationCoordinate2D returns integers for latitude and longitude instead of double

I'm using CLLocation to get the current location as follows:
-(void)loadCurrentLocation{
if (manager==nil) {
manager=[[CLLocationManager alloc]init];
}
manager.delegate=self;
manager.desiredAccuracy=kCLLocationAccuracyBest;
[manager startUpdatingLocation];
}
- (void) viewDidLoad {
[super viewDidLoad];
[self loadCurrentLocation];
}
-(void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
CLLocation *loc=newLocation;
if (loc!=nil) {
self.latitude=loc.coordinate.latitude; //1
self.longitude=loc.coordinate.longitude; //2
NSLog(#"Gained Latitude:%.f",self.latitude);
NSLog(#"Gained Longitude:%.f",self.longitude);
}
}
Given that latitude and longitude are declared as follows in the .h file:
#interface Prayers :UIViewController<CLLocationManagerDelegate>
#property double longitude;
#property double latitude;
#end
the problem is that the returned values at lines 1 & 2 are integers like 30 and 31 and i was expecting them like 31.377033600000004000 and 30.016893900000000000, so why the returned values are integers instead of double ? thanks in advance
If the types weren't what you expect, Xcode would likely be giving you conversion warnings. What makes you think they aren't doubles you are getting back? Maybe the framework is just rounding to the nearest degree and returning that as a double?
Another possibility. what if your log looked like
NSLog(#"Gained Latitude:%.2f",self.latitude);
Does that print more accuracy (note, the 2 in the format).
Maybe even trying boxing them as an NSNumber and see what that prints:
NSLog(#"Gained Latitude:%#", #(self.latitude));

Display the distance between a user's current location and an annotation in a Label

I want to display the distance between a user's current location and another annotation (displayed on my MapView) in a label on my custom table cell.
Each cell displays the name of a cafe (nameLabel), and underneath, I want it to display their distance away from each cafe (distanceLabel).
My MapViewController.m uses this code to calculate the distance between a user's current location and the closest cafes:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
for (MapViewAnnotation *annotation in self.mapView.annotations) {
CLLocationCoordinate2D coord = [annotation coordinate];
CLLocation *userLocation = [[CLLocation alloc] initWithLatitude:coord.latitude longitude:coord.longitude];
annotation.distance = [newLocation distanceFromLocation:userLocation];
CLLocationDistance calculatedDistance = [userLocation distanceFromLocation:userLocation];
annotation.distance = calculatedDistance;
}
I've already set up my custom cell, I just want to know what I should put into my TableView code (TableViewController.m) in order to display the Calculated Distance inside of my text label (called distanceLabel).
E.g. how do I finish this line?
cell.distanceLabel.text =
UPDATE
Just tried adding the reference to my TableViewController.h, but xcode keeps throwing me the error "Redefinition of 'CLLocationDistance' as different kind of symbol".
#class CLLocationDistance;
#property (nonatomic, strong) CLLocationDistance *calculatedDistance;
UPDATE
.h file
****UPDATE**
**.m file****
Make a forward reference for CLLocationDistance calculatedDistance in fx. Your .h . CLLocationDistance is typedef as a double, a prmitive data type, so don't use a pointer in your forward reference (CLLocationDistance calulatedDistance; or #property CLLocationDistance calulatedDistance;). Then do the following:
cell.distanceLabel.text = [NSString stringWithFormat:#"%f", calculatedDistance];
So infact you dont have to create another/new double and assign it to calculatedDistance. Sorry for any confusion..:)

how to get two locations and send them to server - objective-c

I started with objective-c programing, and now I can get one GPS location and send it to my server. this is my code:
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
[manager stopUpdatingLocation];
if(newLocation != nil){
float lat = newLocation.coordinate.latitude ;
float longt = newLocation.coordinate.longitude ;
uint8_t location[BUFFER_SIZE] ={0};
sprintf((char *)location, "(%f,%f)",lat , long) ;
[self writeToServer:location size:strlen((char *)location)] ;
}
}
When "writeToServer" is responsible for sending the data.
Now, how can I change this method to get two locations, in interval of 10 second, then send these two locations?
Many thans!

Latitude Longitude IOS 4.3

I´m following the http://www.switchonthecode.com/tutorials/getting-your-location-in-an-iphone-application tutorial, but I can´t not get mi latitude and longitude in my Xcode SDK.
- (void)viewDidLoad {
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
int degrees = newLocation.coordinate.latitude;
double decimal = fabs(newLocation.coordinate.latitude - degrees);
int minutes = decimal * 60;
double seconds = decimal * 3600 - minutes * 60;
NSString *lat = [NSString stringWithFormat:#"%d° %d' %1.4f\"",
degrees, minutes, seconds];
//latLabel.text = lat;
degrees = newLocation.coordinate.longitude;
decimal = fabs(newLocation.coordinate.longitude - degrees);
minutes = decimal * 60;
seconds = decimal * 3600 - minutes * 60;
NSString *longt = [NSString stringWithFormat:#"%d° %d' %1.4f\"",
degrees, minutes, seconds];
NSLog(#"%# %#",longt, lat);
}
It don´t show me the latitude and longitude in the Console.
Help me please.
Your code looks fine. If it does not work - the issue is not here.
Make sure:
You running it on a device (not emulator)
Your device has SIM installed and connected to cellular network
It's very good idea to have the device connected to WiFi with Internet access.
All these things will help GPS to fix the position faster using assisted GPS.
Also, take into account that Core Location returns last known position almost immediately. It's stale and may be wrong, but provided immediately. If do not getting anything at all - it looks like the issue with Core Location on your device, not with the application.
Also, it's good idea to implement locationManager:didFailWithError: method to catch possible errors. Like disabled GPS.
Here is example for this method:
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"GPS Error: %#", [error localizedDescription]);
}
GPS position fixing may take few minutes for 3Gs and early, and about 10 seconds for 4 and 4S (assuming clear sky view in both cases)

Why do I get extra location coordinate points when my iPhone app first launches?

I am working an iPhone app which is using CLLocationManager. When a user goes for a run, it shows the run path on a mapView. I am drawing the running path on mapView using following code:
double leastDistanceToRecord = 0.0000905;
- (void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
if (newLocation.horizontalAccuracy >= 0) {
if (!runoPath)
{
NSLog(#"in !runoPath if");
// This is the first time we're getting a location update, so create
// the RunoPath and add it to the map.
runoPath = [[RunoPath alloc] initWithCenterCoordinate:newLocation.coordinate];
[map addOverlay:runoPath];
self.currentRunData = [[RunData alloc] init];
[currentRunData startPointLocation:newLocation];
// On the first location update, zoom map to user location
MKCoordinateRegion region =
MKCoordinateRegionMakeWithDistance(newLocation.coordinate, 1000, 1000);
[map setRegion:region animated: NO];
}
else
{
// This is a subsequent location update.
// If the runoPath MKOverlay model object determines that the current location has moved
// far enough from the previous location, use the returned updateRect to redraw just
// the changed area.
double latitudeChange = fabs(newLocation.coordinate.latitude - oldLocation.coordinate.latitude);
double longitudeChange = fabs(newLocation.coordinate.latitude - oldLocation.coordinate.longitude);
if (latitudeChange > leastDistanceToRecord || longitudeChange > leastDistanceToRecord) {
MKMapRect updateRect = [runoPath addCoordinate:newLocation.coordinate];
if (!MKMapRectIsNull(updateRect))
{
// There is a non null update rect.
// Compute the currently visible map zoom scale
MKZoomScale currentZoomScale = map.bounds.size.width / map.visibleMapRect.size.width;
// Find out the line width at this zoom scale and outset the updateRect by that amount
CGFloat lineWidth = MKRoadWidthAtZoomScale(currentZoomScale);
updateRect = MKMapRectInset(updateRect, -lineWidth, -lineWidth);
// Ask the overlay view to update just the changed area.
[runoPathView setNeedsDisplayInMapRect:updateRect];
}
// [currentRunData updateLocation:oldLocation toNewLocation: newLocation];
}
[currentRunData updateLocation:oldLocation toNewLocation: newLocation];
// }
}
}
}
The problem is that when I start a run, I get some extra points and then because of those points I get an extraneous line on mapView that does not reflect the actual run. It even happens when I install the app on my iPhone and run it for the first time. I don't know why it's adding those extra points. Can anyone help me with that? Thanks in advance.
The first location you get is usually a cached location and is old. You can check the age of the location and if it is old (>60 seconds or whatever) then ignore that location update. See this answer here.
--EDIT-- If you are still having problems, put this code in didUpdateToLocation: and show us the actual output from NSLog (you can edit your question and add the output):
NSTimeInterval age = -[newLocation.timestamp timeIntervalSinceNow];
NSLog(#"age: %0.3f sec, lat=%0.2f, lon=%0.2f, hAcc=%1.0f",
age, newLocation.coordinate.latitude, newLocation.coordinate.longitude,
newLocation.horizontalAccuracy);