Friday, September 3, 2010

How to Create Human-readable Geo Coordinate Strings

How to create human-readable coordinate strings, a code snippet that I wrote long time ago. Released here as a reminder for The Next Time (there's always a next time):
CLLocationCoordinate2D loc = mapView.userLocation.coordinate;

BOOL loc_NS;
if (loc.latitude > 0)
{
    loc_NS = YES;
}
else
{
    loc_NS = NO;
    loc.latitude *= -1;
}

int lat_d = floor(loc.latitude);
loc.latitude -= lat_d;
loc.latitude *= 60;
int lat_m = floor(loc.latitude);
loc.latitude -= lat_m;
loc.latitude *= 60;
int lat_s = floor(loc.latitude);

BOOL loc_WE;
if (loc.longitude > 0)
{
    loc_WE = NO;
}
else
{
    loc_WE = YES;
    loc.longitude *= -1;
}

int lon_d = floor(loc.longitude);
loc.longitude -= lon_d;
loc.longitude *= 60;
int lon_m = floor(loc.longitude);
loc.longitude -= lon_m;
loc.longitude *= 60;
int lon_s = floor(loc.longitude);

location.text = [NSString stringWithFormat:@"Location: %d°%d′%d″%@ %d°%d′%d″%@",
    lat_d, lat_m, lat_s, loc_NS ? @"N" : @"S",
    lon_d, lon_m, lon_s, loc_WE ? @"W" : @"E"];
Based on Wikipedia article about Geographic coordinate conversion.

No comments:

Post a Comment