how to get the current location in latitude and longitude in objective c

大兔子大兔子 提交于 2019-12-02 18:37:50

Test the application on real device. The Simulator will always show you the default value for Latitude and Longitude. Also make sure that the location services are enabled on your device.

Hossam Ghareeb

You can add this method where you need to get the current latitude and longitude:

-(CLLocationCoordinate2D) getLocation{
    CLLocationManager *locationManager = [[[CLLocationManager alloc] init] autorelease];
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    locationManager.distanceFilter = kCLDistanceFilterNone;
    [locationManager startUpdatingLocation];
    CLLocation *location = [locationManager location];
    CLLocationCoordinate2D coordinate = [location coordinate];

    return coordinate;
}

And to call it use:

CLLocationCoordinate2D coordinate = [self getLocation];
NSString *latitude = [NSString stringWithFormat:@"%f", coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:@"%f", coordinate.longitude];

NSLog(@"*dLatitude : %@", latitude);
NSLog(@"*dLongitude : %@",longitude);

You have to test location service in device, not simulator, though you can enable location simulation on simulator, see my image attachment, the circled icon. But it won't be your exact location! But at least you can verify your code is working

You need to test it on a device to get your current location's latitude and longitude, i'm guessing you are getting Cupertino's latitude and longitude which is a default.

First You should enable Location Service in your Simulator. Debug -> Location. Most of the case you will be getting lat and long values of Cupertino. And you can set Custom locations for this option by selecting the second option(Custom Location). These option will automatically triggered when we are selecting location when runtime in Debugging area.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!