objective-c - CLGeocoder 反向地理编码位置。第一次在 [placemarks count = 0]?

标签 objective-c ios geolocation mkmapview clgeocoder

我是 ObjC 的新手,我正在努力使用 CLGeocoder。我希望能够使用 reverseGeocodeLocation获取一个字符串,其中包含当用户按下完成按钮时我传递给我的委托(delegate)的用户位置。

所以用户触发了一个MapViewController的显示,我在viewDidLoad中调用reverseGeocodeLocation但是 [placemarks count = 0]这是第一次,我没有地标来获取我需要的信息。用户第二次触发 MapViewController 的显示时,placemarks 数组已被填充并且一切正常。

我怀疑这与 reverseGeocodeLocation 是一个异步调用有关 - 但我不知道如何解决这个问题。我曾尝试在线搜索,但似乎没有什么能帮助我理解我做错了什么以及如何解决这个问题。提前致谢。

@interface MapViewController ()
@property (strong, nonatomic) CLGeocoder *geocoder;
@property (readwrite, nonatomic) NSString *theLocationName;
@end

@implementation MapViewController
@synthesize mapView, geocoder, delegate = _delegate, theLocationName = _theLocationName;

- (void)viewDidLoad
{
[super viewDidLoad];

self.mapView.delegate=self;
self.mapView.showsUserLocation = YES;

[self theUserLocation];
}

-(void)theUserLocation
{
if (!geocoder)
{
    geocoder = [[CLGeocoder alloc] init];
}

MKUserLocation *theLocation;
theLocation = [self.mapView userLocation];

[geocoder reverseGeocodeLocation:theLocation.location 
               completionHandler:^(NSArray* placemarks, NSError* error)
 {
     if ([placemarks count] > 0)
     {
         CLPlacemark *placemark = [placemarks objectAtIndex:0];

         [self setTheLocationName: placemark.locality];

     }
 }];

- (IBAction)done:(id)sender 
{

[[self delegate] mapViewControllerDidFinish:self locationName:[self theLocationName]];

}

@end

最佳答案

这不是您问题的确切答案,但是,如果您可以切换到除 CLGeocoder 之外的其他解决方案,那么以下功能可以帮助您从给定的纬度、经度获取地址

#define kGeoCodingString @"http://maps.google.com/maps/geo?q=%f,%f&output=csv" //define this at top

-(NSString *)getAddressFromLatLon:(double)pdblLatitude withLongitude:(double)pdblLongitude
{
    NSString *urlString = [NSString stringWithFormat:kGeoCodingString,pdblLatitude, pdblLongitude];
    NSError* error;
    NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSASCIIStringEncoding error:&error];
    locationString = [locationString stringByReplacingOccurrencesOfString:@"\"" withString:@""];
    return [locationString substringFromIndex:6];
}

信用:Selected Answer to this question

关于objective-c - CLGeocoder 反向地理编码位置。第一次在 [placemarks count = 0]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11287738/

相关文章:

iphone - 尝试从祖鲁时间的 UTC 字符串获取日期时为 Nil NSDate

objective-c - Objective-C/Cocoa 中的绑定(bind)与 IBOutlets

ios - 为什么 URL 仅在几秒钟后才在 UIWebView 中显示为超链接?

ios - 如何以编程方式关闭自动亮度?

python - 寻找 Python/Django 框架来查询数据库中的 GeoLocation 数据

objective-c - 查看 Objective-c 的汇编代码

objective-c - 不了解 Objective c 中的基本属性和方法

ios - 将图像设置为 iOS 中的导航栏后退按钮

javascript - 地理定位在移动设备上不起作用,但在我的桌面上起作用

ios - verseGeocodeLocationCompletionHandler 失败并显示 "[TNSDictionaryAdapter coordinate]: unrecognized selector sent to instance"