目标C-如何将度-分-秒转换为双精度 [英] Objective C - how to convert Degree-Minute-Second to Double

查看:133
本文介绍了目标C-如何将度-分-秒转换为双精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的实际问题是-当地图上的 coordinate 值以度-分-秒-第二形式(以字符串形式)而不是双精度形式提供时,如何获取CLLocation对象.

My actual problem is - How to obtain a CLLocation Object when the coordinate value on the map is available in Degree-Minute-Second form (as a String), instead of Double.

因此,我正在寻找一种将度一分秒转换为双精度的方法,可以用来形成CLLocation对象.

So, I am Looking for a way to convert Degree-Minute-Second to Double, which i can use to form a CLLocation object.

推荐答案

在弄清楚这一点时,我想到了一个更简洁的答案

I came up with a bit of a cleaner answer when figuring this out

// split the string to deal with lat and lon separately
NSArray *parts = [dmsString componentsSeparatedByString:@","];
NSString *latStr = parts[0];
NSString *lonStr = parts[1];

// convert each string
double lat = [self degreesStringToDecimal:latStr];
double lon = [self degreesStringToDecimal:lonStr];

// init your location object
CLLocation *loc = [[CLLocation alloc] initWithLatitude:lat longitude:lon];

魔术

- (double)degreesStringToDecimal:(NSString*)string
{
    // split the string
    NSArray *splitDegs = [string componentsSeparatedByString:@"\u00B0"];  // unicode for degree symbol
    NSArray *splitMins = [splitDegs[1] componentsSeparatedByString:@"'"];
    NSArray *splitSecs = [splitMins[1] componentsSeparatedByString:@"\""];

    // get each segment of the dms string
    NSString *degreesString = splitDegs[0];
    NSString *minutesString = splitMins[0];
    NSString *secondsString = splitSecs[0];
    NSString *direction = splitSecs[1];

    // convert degrees
    double degrees = [degreesString doubleValue];

    // convert minutes
    double minutes = [minutesString doubleValue] / 60;  // 60 degrees in a minute

    // convert seconds
    double seconds = [secondsString doubleValue] / 3600; // 60 seconds in a minute, or 3600 in a degree

    // add them all together
    double decimal = degrees + minutes + seconds;

    // determine if this is negative. south and west would be negative values
    if ([direction.uppercaseString isEqualToString:@"W"] || [direction.uppercaseString isEqualToString:@"S"])
    {
        decimal = -decimal;
    }

    return decimal;
}

请注意,我仅使用威斯康星州的坐标(北和西)对此进行了测试.我正在使用此工具来验证我的计算.

Note that I've only tested this with coordinates in Wisconsin, which is North and West. I'm using this tool to verify my calculations.

这篇关于目标C-如何将度-分-秒转换为双精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆