views:

43

answers:

2

How can I store the latitude and longitude coordinates of the iPhone's current location into two different float variables?

A: 

This tutorial will help you do exactly that.

Here is the relevant code from the tutorial that you would be interested in:

- (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];
  longLabel.text = longt;
}
Chetan
A: 

Chetan's answer is excellent and will give you the lat and long in degrees. Just in case you're only interested in storing the lat and long in units that you can then use for comparison with other locations you might just do the following:

- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
       fromLocation:(CLLocation *)oldLocation {
CLLocationDegrees latitude = newLocation.coordinate.latitude;
CLLocationDegrees longitude = newLocation.coordinate.longitude;
...
}

If you want to keep these then you'd want to provide some sort of storage for the values. Otherwise they'll go out of scope at the end of the method.

Note that CLLocationDegrees is merely a double with a pretty name.

Keep in mind that a CLLocation.coordinate is a neat struct that you may store as a CLLocationCoordinate2D - much more elegant to keep these values together as they retain a little more context.

Grumpy Chuck