3

I have a latitude/longitude decimal coordinates that I would like to convert to points that will fit within the area of the iPad coordinate system.

My code takes in a latitude/longitude coordinates and converts them to cartesian coordinates (based on this question: convert to cartesian coordinates) The results of the conversion are (2494.269287, 575.376465).

Here is my code (no compile or runtime errors):

#define EARTH_RADIUS 6371

- (void)drawRect:(CGRect)rect
{
    CGPoint latLong = {41.998035, -116.012215};

    CGPoint newCoord = [self convertLatLongCoord:latLong];

    NSLog(@"Cartesian Coordinate: (%f, %f)",newCoord.x, newCoord.y);

    //Draw dot at coordinate
    CGColorRef darkColor = [[UIColor colorWithRed:21.0/255.0
                                            green:92.0/255.0
                                             blue:136.0/255.0
                                            alpha:1.0] CGColor];
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, darkColor);
    CGContextFillRect(context, CGRectMake(newCoord.x, newCoord.y, 100, 100));

}

-(CGPoint)convertLatLongCoord:(CGPoint)latLong
{
    CGFloat x = EARTH_RADIUS * cos(latLong.x) * cos(latLong.y);
    CGFloat y = EARTH_RADIUS * cos(latLong.x) * sin(latLong.y);

    return CGPointMake(x, y);
}

How can I convert the decimal coordinates to coordinates that will show up on an iPad screen?

Community
  • 1
  • 1
tentmaking
  • 2,076
  • 4
  • 30
  • 53
  • Instead of `EARTH_RADIUS`, multiply by the screen width and height. –  Apr 20 '13 at 19:20
  • @H2CO3 - What do you mean by that? An retina iPad resolution is 2048 X 1536. I multiplied those together and the coordinates produced were much larger than before. – tentmaking Apr 20 '13 at 19:28
  • Nah, it's 1024 * 768 **points.** Quartz doesn't work with pixels, it works with points. –  Apr 20 '13 at 19:30
  • That still produces vary large numbers. – tentmaking Apr 20 '13 at 19:36

1 Answers1

10

Your convertLatLongCoord: method makes no attempt to adjust the resulting point to screen coordinates. As written, you can get x and y values in the range -EARTH_RADIUS to +EARTH_RADIUS. These need to be scaled to fit the screen.

Something like the following should help:

- (CGPoint)convertLatLongCoord:(CGPoint)latLong {
    CGFloat x = EARTH_RADIUS * cos(latLong.x) * cos(latLong.y) * SCALE + OFFSET;
    CGFloat y = EARTH_RADIUS * cos(latLong.x) * sin(latLong.y) * SCALE + OFFSET;

    return CGPointMake(x, y);
}

SCALE and OFFSET should be a value determined as follows:

CGSize screenSize = [UIScreen mainScreen].applicationFrame.size;
CGFloat SCALE = MIN(screenSize.width, screenSize.height) / (2.0 * EARTH_RADIUS);
CGFloat OFFSET = MIN(screenSize.width, screenSize.height) / 2.0;

This assumes you want the map to fill the smallest screen dimension.

rmaddy
  • 314,917
  • 42
  • 532
  • 579