在地图加载之前查找用户位置

时间:2010-03-12 20:34:31

标签: iphone cocoa-touch mapkit

我正在尝试使用以下方式查找用户的位置:

CLLocationCoordinate2D _location;
CLLocation *userLoc = nil;
if(appDelegate.clLocationManager.locationServicesEnabled){
    userLoc = mapView.userLocation.location;
    _location = userLoc.coordinate;
}

问题是我还没有初始化地图,所以上面的内容不起作用。有没有办法在不使用mapkit的情况下获取用户的位置?或者我应该使用不同的技术吗?

2 个答案:

答案 0 :(得分:1)

要获取用户的位置,您需要在尝试阅读位置信息之前实际“启动”位置管理器。我建议您查看Apple的LocateMe示例。

LocateMe Sample Code

简而言之,获取用户的位置信息可以分两步完成:

- (void)viewDidLoad {
    [[self locationManager] startUpdatingLocation];
}

- (CLLocationManager *)locationManager { 

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

    NSLog(@"%s, Creating new Location Manager instance.", __FUNCTION__);
    locationManager = [[CLLocationManager alloc] init]; 
    locationManager.desiredAccuracy = kCLLocationAccuracyBest; 
    locationManager.distanceFilter = DISTANCE_FILTER_VALUE;
    locationManager.delegate = self; 

    return locationManager; 
}

......然后,

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { 
    NSLog(@"%s, location manager returned a new location.", __FUNCTION__);

    // Check if location is valid (or good enough for us), 
    // and then process the location
    if ([self locationIsValid:newLocation]) {
            [self processLocation:newLocation];

            // Very important! When your done with it, stop the location manager
            [[self locationManager] sopUpdatingLocation];

            // (Maybe even) clear it
            locationManager.delegate = nil;
            [locationManager release];
            locationManager = nil;
    }
}

希望这有帮助!

答案 1 :(得分:0)

我几乎删除了这个问题,但看到有人给了它一个投票。这似乎是答案:

CLLocationCoordinate2D _location;
CLLocation *userLoc = nil;
if(appDelegate.clLocationManager.locationServicesEnabled){
    userLoc = appDelegate.clLocationManager.location;
    _location = userLoc.coordinate;
}

appDelegate只是对我的位置管理器实例所在的应用程序委托的引用。