【问题标题】:trying to retrieve current location in iOS试图在 iOS 中检索当前位置
【发布时间】:2013-06-22 06:47:16
【问题描述】:

我正在构建一个应用程序,该应用程序需要我找到指定位置与我当前位置之间的距离。 我正在使用CLLocationManager,但检索到的坐标为 0,0,尽管我在模拟器中指定了自定义位置。这是代码: .m 文件

@property (nonatomic, strong) CLLocationManager *locationManager2;
...
@synthesize locationManager2;
- (CLLocationManager *)locationManager2 {

if (locationManager2 != nil) {
    return locationManager2;
}

locationManager2 = [[CLLocationManager alloc] init];
[locationManager2 setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
[locationManager2 setDelegate:self];

return locationManager2;
}
 ...
 ...
 ...
  CLLocation *locationHome = [locationManager2 location];

NSLog(@"%f",locationHome.coordinate.latitude);

纬度记录为零。我的代码有什么问题吗?

【问题讨论】:

  • 模拟器不支持提供位置。您必须使用设备。
  • 这不是位置管理器的工作方式。您必须启动位置服务并等待对委托方法的调用。您不能可靠地只创建一个位置管理器对象并查询其位置。这是异步发生的。请参阅Location Awareness Programming Guide
  • 我使用 iOS 6 并在模拟器中获得 nil。正如 Rob 建议的那样,试试这个:[locationManager2 startUpdatingLocation]; CLLocation * locationHome = locationManager2.location; [locationManager2 stopUpdatingLocation];

标签: ios cllocationmanager cllocation


【解决方案1】:

输入这段代码,让我知道你在控制台得到了什么。

此代码基于 iOS 6。

CLLocationManager *locationManager = [[CLLocationManager alloc] init];
if ([CLLocationManager locationServicesEnabled])
{
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    locationManager.distanceFilter = kCLDistanceFilterNone;
    [locationManager startUpdatingLocation];
}

location = [locationManager location];
CLLocationCoordinate2D coordinate = [location coordinate];;
MKCoordinateRegion region;
region.center=coordinate;
MKCoordinateSpan span;
span.latitudeDelta=10.015;
span.longitudeDelta=10.015;
region.span=span;
[mapView setRegion:region];

NSString *str=[[NSString alloc] initWithFormat:@" latitude:%f longitude:%f",coordinate.latitude,coordinate.longitude];
NSLog(@"%@",str);

【讨论】:

    猜你喜欢
    • 2014-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-04
    • 2013-02-05
    • 1970-01-01
    相关资源
    最近更新 更多