简体   繁体   中英

Show current location in map ios with CLLocationmanager

I am trying to show current location in map but fails . It gives error as location is null . Which option should be selected in simulator debug location options . If i tries to use none than it returns null location nd for custom it gives location of pre decided coordinate . i wanna get current location !

I don't think you can get current location through simulator. All that you can do is give your current location's latitude and longitude in Debug -> Location -> Custom Location. This will be used as current location by your simulator. Other option is to add GPX file to your project scheme.Edit Scheme -> Options -> Check Allow Location Simulation. Add GPX file to your project. 添加GPX文件

Above settings are for debugging in simulator.It runs based on current location in real device even though these settings are not done(For faultless code).

create object first

 CLLocationManager *locationManager = [[CLLocationManager alloc] init];
 locationManager.delegate = self;

#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
 if(IS_OS_8_OR_LATER)
 {
    [locationManager requestAlwaysAuthorization];
    [locationManager requestWhenInUseAuthorization];
 }
[locationManager startUpdatingLocation];

//Below two lines give you current location (lat-long).
Latitude = [NSString stringWithFormat:@"%f",locationManager.location.coordinate.latitude];
NSLog(@"Lat====%@",Latitude);

Longitude = [NSString stringWithFormat:@"%f",locationManager.location.coordinate.longitude];
NSLog(@"Log====%@",Longitude);

you can add this in AppDelegate.h

@property (nonatomic, strong)  CLLocationManager *locationManager;

You can use this for fetch current location. you can add this code in AppDelegate.m file

if ([CLLocationManager locationServicesEnabled]) {
        if (!_locationManager) {
            _locationManager = [[CLLocationManager alloc] init];
            _locationManager.delegate = self;
            _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
            _locationManager.distanceFilter = 10.0;
            [self.locationManager startMonitoringSignificantLocationChanges];
        }
        // Check for iOS 8. Without this guard the code will crash with "unknown selector" on iOS 7.
        if ([_locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
            [_locationManager requestAlwaysAuthorization];
        [_locationManager startUpdatingLocation];
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM