Search code examples
iphoneios5core-location

How to get device current latitude and longitude for IPhone device


I'm developing an app were I would like to get device current latitude and longitude for IPhone. Is it possible to obtain this information without using GPS.

Thanks


Solution

  • you can use CoreLocation framework

    The Core Location framework has one important class CLLocationManager.

    The CLLocationManager class handles sending out updates to a delegate anytime the location is changed. it uses the delegate CLLocationManagerDelegate protocol.

    you can use it like

    #import <CoreLocation/CoreLocation.h>
    
    @interface ViewController : UIViewController 
      <CLLocationManagerDelegate>
    {
      CLLocationManager *locationManager;
    
    }
    

    set up locationManager like this in viewDidLoad

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

    implement the below delegate mehod for getting changed location

     - (void)locationManager:(CLLocationManager *)manager
        didUpdateToLocation:(CLLocation *)newLocation
               fromLocation:(CLLocation *)oldLocation
    {
      NSInteger degrees = newLocation.coordinate.latitude;
      double decimal = fabs(newLocation.coordinate.latitude - degrees);
      int minutes = decimal * 60;
      double seconds = decimal * 3600 - minutes * 60;
      NSString *lattitudeStr = [NSString stringWithFormat:@"%d° %d' %1.4f\"", 
                       degrees, minutes, seconds];
      lattitudeLabel.text = lattitudeStr;
      degrees = newLocation.coordinate.longitude;
      decimal = fabs(newLocation.coordinate.longitude - degrees);
      minutes = decimal * 60;
      seconds = decimal * 3600 - minutes * 60;
      NSString *longitudeStr = [NSString stringWithFormat:@"%d° %d' %1.4f\"", 
                         degrees, minutes, seconds];
      longitudeLabel.text = longitudeStr;
    }