我有一个纬度/经度十进制坐标,我想将其转换为适合 iPad 坐标系区域的点。
我的代码接受纬度/经度坐标并将它们转换为笛卡尔坐标(基于这个问题:转换为笛卡尔坐标)转换的结果是(2494.269287, 575.376465)。
这是我的代码(没有编译或运行时错误):
#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);
}
如何将小数坐标转换为 iPad 屏幕上显示的坐标?
您的
convertLatLongCoord:
方法不会尝试将结果点调整为屏幕坐标。如前所述,您可以获得 x
到 y
范围内的 -EARTH_RADIUS
和 +EARTH_RADIUS
值。这些需要缩放以适合屏幕。
类似以下内容应该有所帮助:
- (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
和 OFFSET
应为如下确定的值:
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;
这假设您希望地图填充最小的屏幕尺寸。
@rmaddy 答案的 Swift 版本:
var point: CGPoint {
let earthRadius = 6371.0 // in KM
let size = UIScreen.main.bounds // depecrated use something else
let scale = min(size.width, size.height) / (2.0 * earthRadius)
let offset = min(size.width, size.height) / 2.0
let x = earthRadius * cos(self.latitude) * cos(self.longitude) * scale + offset
let y = earthRadius * cos(self.latitude) * sin(self.longitude) * scale + offset
return .init(x: x, y: y)
}