iOS:Watch Kit获取当前位置并在地图上显示

时间:2015-10-23 13:55:00

标签: ios objective-c watchkit

我有一个iOS应用,它使用用户当前位置来显示用户当前位置和目标点之间的路线/距离。我能够在地图上显示目的地点,但是当我尝试使用CLlocationManager获取用户的当前位置时,它返回坐标(0,0)。以下是我检索用户位置的代码。

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

另外,我有#import< CoreLocation / CoreLocation.h>在我的.h文件和< CLLocationManagerDelegate>

2 个答案:

答案 0 :(得分:4)

请尝试以下代码:

@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
}

答案 1 :(得分:-2)

如果你没有实现这个: (使用属性检查器或以编程方式)

self.mapView.showsUserLocation = YES

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