Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need to find my current location with CoreLocation, I tried multiple methods but so far my CLLocationManager has only returned 0's.. (0.000.00.000).

Here's my code (updated to work):

Imports:

#import <CoreLocation/CoreLocation.h>

Declared:

IBOutlet CLLocationManager *locationManager;
IBOutlet UILabel *latLabel;
IBOutlet UILabel *longLabel;

Functions:

- (void)getLocation { //Called when needed
    latLabel.text  = [NSString stringWithFormat:@"%f", locationManager.location.coordinate.latitude]; 
    longLabel.text = [NSString stringWithFormat:@"%f", locationManager.location.coordinate.longitude];
}

- (void)viewDidLoad {
    locationManager = [[CLLocationManager alloc] init];
    locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
    [locationManager startUpdatingLocation];
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
820 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can find your location using CoreLocation like this:

import CoreLocation:

#import <CoreLocation/CoreLocation.h>

Declare CLLocationManager:

CLLocationManager *locationManager;

Initialize the locationManager in viewDidLoad and create a function that can return the current location as an NSString:

- (NSString *)deviceLocation {
    return [NSString stringWithFormat:@"latitude: %f longitude: %f", locationManager.location.coordinate.latitude, locationManager.location.coordinate.longitude];
}

- (void)viewDidLoad
{
    locationManager = [[CLLocationManager alloc] init];
    locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
    [locationManager startUpdatingLocation];
}

And calling the deviceLocation function will return the location as expected:

NSLog(@"%@", [self deviceLocation]);

This is just an example. Initializing CLLocationManager without the user being ready for it isn't a good idea. And, of course, locationManager.location.coordinate can be used to get latitude and longitude at will after CLLocationManager has been initialized.

Don't forget to add the CoreLocation.framework in your project settings under the Build Phases tab (Targets->Build Phases->Link Binary).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...