Convert decimal coordinate into degrees, minutes, seconds, direction

trapper picture trapper · Jan 13, 2012 · Viewed 14.6k times · Source

I have the following so far, but can't figure out a tidy way to get the direction letters in without a bunch of messy if statements. Any ideas? Ideally I'd like to extend the CLLocation class with a category to do this.

-(NSString *)nicePosition{

double latitude = [self.latitude doubleValue];
double longitude = [self.longitude doubleValue];

int latSeconds = (int)round(latitude * 3600);
int latDegrees = latSeconds / 3600;
latSeconds = abs(latSeconds % 3600);
int latMinutes = latSeconds / 60;
latSeconds %= 60;

int longSeconds = (int)round(longitude * 3600);
int longDegrees = longSeconds / 3600;
longSeconds = abs(longSeconds % 3600);
int longMinutes = longSeconds / 60;
longSeconds %= 60;

//TODO: Use N,E,S,W notation in lat/long

return [NSString stringWithFormat:@"%i° %i' %i\", %i° %i' %i\"", latDegrees, latMinutes, latSeconds, longDegrees, longMinutes, longSeconds];
}

For the record I did the following.

-(NSString *)nicePosition{

double latitude = [self.latitude doubleValue];
double longitude = [self.longitude doubleValue];

int latSeconds = (int)round(abs(latitude * 3600));
int latDegrees = latSeconds / 3600;
latSeconds = latSeconds % 3600;
int latMinutes = latSeconds / 60;
latSeconds %= 60;

int longSeconds = (int)round(abs(longitude * 3600));
int longDegrees = longSeconds / 3600;
longSeconds = longSeconds % 3600;
int longMinutes = longSeconds / 60;
longSeconds %= 60;

char latDirection = (latitude >= 0) ? 'N' : 'S';
char longDirection = (longitude >= 0) ? 'E' : 'W';

return [NSString stringWithFormat:@"%i° %i' %i\" %c, %i° %i' %i\" %c", latDegrees, latMinutes, latSeconds, latDirection, longDegrees, longMinutes, longSeconds, longDirection];
}

Answer

user529758 picture user529758 · Jan 13, 2012

Standard way:

char lonLetter = (lon > 0) ? 'E' : 'W';
char latLetter = (lat > 0) ? 'N' : 'S';