我有一个地理编码器方法,我希望它返回它为我生成的 CLLocationCoordinate2D。
- (CLLocationCoordinate2D)geocode{
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(0,0);
[geocoder geocodeAddressDictionary:self.placeDictionary completionHandler:^(NSArray *placemarks, NSError *error) {
if([placemarks count]) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
CLLocation *location = placemark.location;
coordinate = location.coordinate;
} else {
NSLog(@"error");
}
}];
return coordinate;
}
但是,该行coordinate = location.coordinate
会产生错误。XCode 说coordinate
是一个不可赋值的变量。有人看到我做错了什么吗?
更新:
在遵循塞巴斯蒂安的建议后,我得到了要编译的代码,但是coordinate
没有正确设置。如果您查看我在方法中放入的两个 NSLog 语句,第一个语句会打印出我需要分配给的正确坐标coordinate
,但是一旦 if 语句退出,coordinate
就会返回设置为 (0,0 )。第二个 NSLog 语句打印 (0,0)。有谁知道我该如何解决这个问题?
- (CLLocationCoordinate2D)geocode{
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
__block CLLocationCoordinate2D geocodedCoordinate = CLLocationCoordinate2DMake(0,0);
[geocoder geocodeAddressDictionary:self.placeDictionary completionHandler:^(NSArray *placemarks, NSError *error) {
if([placemarks count]) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
CLLocation *location = placemark.location;
geocodedCoordinate = location.coordinate;
NSLog(@"%f, %f", coordinate.longitude, coordinate.latitude);
} else {
NSLog(@"error");
}
}];
NSLog(@"%f, %f", coordinate.longitude, coordinate.latitude);
return coordinate;
}