开发者

Finding user location before map loads

开发者 https://www.devze.com 2022-12-23 05:49 出处:网络
I\'m trying to find the user\'s location using: CLLocationCoordinate2D _location; CLLocation *userLoc = nil;

I'm trying to find the user's location using:

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

The problem is that I haven't yet in开发者_高级运维itialized the map so the above doesn't work. Is there a way to get the user's location without using mapkit? Or should I be using a different technique?


To get the user's location you need to actually "start" the location manager before trying to read the Location information. I suggest that you look at LocateMe sample from Apple.

LocateMe Sample Code

In a nutshell, getting user's location information can be done in two steps:

- (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; 
}

... and then,

- (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;
    }
}

Hope this helps!


I almost deleted this question but see somebody gave it an up vote. This seems to be the answer:

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

appDelegate is just a reference to the application delegate, where my location manager instance lives.

0

精彩评论

暂无评论...
验证码 换一张
取 消