2013-06-22 34 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);