字符串转换为CLLocation的纬度和经度

20

我有两个代表纬度和经度的字符串,例如:"-56.6462520",我想将它们分配给一个CLLocation对象以便与我的当前位置进行比较。 我尝试了以下代码,但只收到错误提示:

CLLocation * LocationAtual = [[CLLocation alloc]init];
LocationAtual.coordinate.latitude = @"-56.6462520";
LocationAtual.coordinate.longitude = @"-36.6462520";

然后将该对象与我的实际位置纬度和经度进行比较。您有任何建议吗?


6
Objective-C 的命名规范是使用 camelCase 命名法来命名变量。 - Adam Waite
5个回答

109

您不能直接赋值给coordinate属性 - 它是CLLocation的只读属性。
请使用以下实例方法:

- (instancetype)initWithLatitude:(CLLocationDegrees)latitude
                       longitude:(CLLocationDegrees)longitude

例子:

CLLocation *LocationAtual = [[CLLocation alloc] initWithLatitude:-56.6462520 longitude:-36.6462520];

1
没错,你不能对CLLocation属性进行赋值。 - Hola Soy Edu Feliz Navidad

12

我认为你需要:

LocationAtual.coordinate.latitude = [@"-56.6462520" floatValue];
LocationAtual.coordinate.longitude = [@"-36.6462520" floatValue];

我明白了,我认为转换是正确的,但是我遇到了这个错误:“Lvaule需要作为赋值的左操作数”... - Vinicius Albino
1
http://stackoverflow.com/questions/5527878/lvalue-required-as-left-operand-of-assignment - Robot Woods
3
我无法删除已接受的答案,但我同意AmitP的答案是正确的。我的回答大致上是“你不能将字符串用作数字”。 - Robot Woods
表达式不可赋值。 - Bhumesh Purohit

9

懒人的Swift答案:

var LocationAtual: CLLocation = CLLocation(latitude: -56.6462520, longitude: -36.6462520)

1

CLLocation的坐标实际上是只读值

    @property (nonatomic, readonly) CLLocationCoordinate2D coordinate;

所以将虚拟数据分配给坐标的最佳方法是AMITp的方式。

1
纬度和经度是双精度数值,因此需要按照这种方式进行赋值。
CLLocation *LocationAtual=[[CLLocation alloc] initWithLatitude:[[location objectForKey:@"latitude"] doubleValue] longitude:[[location objectForKey:@"longitude"] doubleValue]]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接