2013-06-22 32 views
-1

我正在构建一个应用程序,要求我查找指定位置与当前位置之间的距离。 我使用的是CLLocationManager,但检索的坐标是0,0,尽管我在模拟器中指定了一个自定义位置。下面的代码: 试图在iOS中检索当前位置

@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); 

的lattitude被记录为zero.Anything错我的代码.m文件?

+0

Simulator不支持提供位置。你必须使用设备。 – Geek

+0

在ios 6中它.. –

+3

这不是位置管理器的工作原理。您必须启动位置服务并等待委托方法的调用。您无法可靠地创建位置管理器对象并查询其位置。这是异步发生的。请参阅[位置感知编程指南](http://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/LocationAwarenessPG/CoreLocation/CoreLocation.html#//apple_ref/doc/uid/TP40009497-CH2-SW9 )。 – Rob

回答

0

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

此代码内置在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);