【问题标题】:Convert string to coordinates in objective-C将字符串转换为objective-C中的坐标
【发布时间】:2014-04-08 17:00:29
【问题描述】:

我使用以下代码将一些坐标转换为字符串:

 label3.text = [NSString stringWithFormat:@"%f%f",
               venue.location.coordinate.latitude,
               venue.location.coordinate.longitude];

但是,我现在想将字符串转换回纬度和经度坐标。我该怎么做?

【问题讨论】:

  • 如果你在两个数字之间加一个分隔符会很有帮助。
  • 几乎可以肯定,重新访问信息的原始来源比摆弄字符串解析更容易。

标签: objective-c string location coordinates


【解决方案1】:

您不能这样做,因为您的代码没有在值之间提供分隔符。因此,您将无法确定是否为字符串

12.3456.78

是以下一对:

12.3 456.78
12.34 56.78
12.345 6.78
12.3456 .78

为了使转换可逆,请使用@"%f %f" 格式(带空格)。现在您可以使用许多不同的方式从字符串中解析回数据 - 例如,sscanf:

float lat, lon;
sscanf([label3.text UTF8String], "%f %f", &lat, &lon);

【讨论】:

  • 这非常有效。非常感谢,花了几个小时试图弄清楚。
【解决方案2】:

如果你用分隔符分隔你的浮点数,像这样:

label3.text = [NSString stringWithFormat:@"%f;%f",
               venue.location.coordinate.latitude,
               venue.location.coordinate.longitude];

然后

CGPoint yourPoint=CGPointMake((NSString*)([[label3.text componentsSeparatedByString:@";"] 
firstObject]).floatValue,(NSString*)([[label3.text componentsSeparatedByString:@";"] lastObject]).floatValue)
//yourPoint.x is latitude, yourPoint.y is longitude

【讨论】:

  • CLLocationCoordinate2D 将是比 CGPoint 更合适的结构。事实上,OP 应该将坐标保存在这样的结构中,而不是从字符串中抓取。
猜你喜欢
  • 2014-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-17
  • 2013-09-01
相关资源
最近更新 更多