2015-10-23 31 views
1

我有一个iOS应用程序,它使用用户当前位置显示用户当前位置和目的地点之间的方向/距离。我能够在地图上显示目的地点,但是当我尝试使用CLlocationManager获取用户的当前位置时,它会返回坐标(0,0)。以下是我检索用户位置的代码。iOS:手表套件获取当前位置并在地图上显示

正在Apple Watch上检索当前位置?

如果是这样,我在这里做错了位置返回(0,0)?

CLLocationManager *locationManager = [[CLLocationManager alloc] init]; 
locationManager.delegate = self; 
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation; 
locationManager.distanceFilter = 5; 
CLLocation *location = locationManager.location; 

CLLocationCoordinate2D myLoc = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude); 

而且,我已经在我的.h文件中#IMPORT < CoreLocation/CoreLocation.h>和< CLLocationManagerDelegate>

+0

没有ü添加所需的键UR plsit像NSLocationAlwaysUsageDescription? –

+0

:(不,我绝对忘了这么做... –

+0

@ Mr.TI已经添加了NSLocationAlwaysUsageDescription到plist,并且在Capabilities选项卡下开启了Maps,你知道locationManager不会返回一个位置的其他原因吗? –

回答

3

试试下面的代码:

@property (nonatomic, strong) CLLocationManager *locationManager; 

- (void)willActivate 
{ 
    self.locationManager = [[CLLocationManager alloc] init]; 
    [self.locationManager setDelegate:self]; 
    [self.locationManager requestLocation]; 
} 

- (void)locationManager:(CLLocationManager *)manager 
    didUpdateLocations:(NSArray *)locations 
{ 
    if ([locations count] == 0) { 
     // error 
     return; 
    } 

    // success 
    self.currentLocation = [locations firstObject]; 
    CLLocationCoordinate2D myLoc = CLLocationCoordinate2DMake(
     self.currentLocation.coordinate.latitude, 
     self.currentLocation.coordinate.longitude); 
} 

- (void)locationManager:(CLLocationManager *)manager 
     didFailWithError:(nonnull NSError *)error 
{ 
    // error 
} 
+0

作品完美,谢谢!对于查找此答案的其他人,忽略didFailWithError方法会导致崩溃,请确保将您的密钥添加到您的手表扩展程序目标上的info.plist中,并启用手表扩展程序目标上功能选项卡下的地图。 –

-2

如果您没有实现这一点: (与属性检查器中或在程序上)

self.mapView.showsUserLocation =是

或者除了告诉mapView用户的位置取决于LocationManager.location

+0

这是在Apple Watch上,WKInterfaceMap上没有一个名为showsUserLocation的属性,您是否知道另一种解决方案? –

+0

道歉,我没有完全阅读,I不知道很多关于Watch Kit Framework的知识...但是Hasardly,什么是返回LocationManager.location? – Lkm

+0

LocationManager.location返回null –

相关问题