Showing posts with label Location. Show all posts
Showing posts with label Location. Show all posts

Thursday, 30 March 2017

Get User Current Location

Location service improve the app by enhancing user experience. Lots of application's features base on location service like finding near places, restaurant and whatever user want to search. Uber, Ola, Nearby and tons of applications are based on location service and display required content on the basis of that. Suppose we are stand on a place and want to search restaurant near current location, in this case we must know user current location and than can display result according to user search.
Now question is how can we get user current location? It is not a difficult task, every language provide in build framework and library for perform this task.
 Apple provide Core Location Framework for obtaining all necessary information regarding user's current location. Core Location Framework provide geographic location of device. Click here to know about Geographic coordinate system.

Lets start the coding stuff to fetch current location of a user.
Add Core Location Framework in the build phase of target under"Link Binary with Library"  section, switch to controller class and import location framework and implement <CLLocationManagerDelegate> and declare an instance of CLLocationManager.

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

Now switch to .m class and add method for fetch current location

@implementation HomeMapViewController
      - (void)viewDidLoad {
              [super viewDidLoad];
              // Do any additional setup after loading the view from its nib.
               [self  getCurrentLocation];
       }
     -(void) getCurrentLocation{
         locationManager = [[CLLocationManager alloc] init];
         locationManager.delegate = self;
         locationManager.desiredAccuracy = kCLLocationAccuracyBest;
         if ([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
             [locationManager requestWhenInUseAuthorization];
         }
         [locationManager startUpdatingLocation];
     }
// define delegate methods of <CLLocationManagerDelegate>
      - (void)locationManager:(CLLocationManager *)manager
         didFailWithError:(NSError *)error{
          NSLog(@"Error to fetch location = %@", error);
     }
     -(void) locationManager:(CLLocationManager *)manager didUpdateLocations:               (NSArray<CLLocation *> *)locations{
         CLLocation *location = [locations lastObject];
         CLLocationCoordinate2D cord = location.coordinate;
         NSLog(@"Current Location\n Latitude - %f \n Longitude - %f", cord.latitude, cord.longitude);
     }@end

Now run the app and allow the application to fetch your current location.
You can see latitude and longitude value of location on  console area. We are successfully getting  current location of device/user.
We can stop location update service any time by using 'stopUpdatingLocation' method. It will be better to stop location service after getting current location. add following  line of code inside of 'didUpdateLocations' method

[locationManager stopUpdatingLocation];

But the problem is, value of location in form of latitude and longitude and it is not in human readable address. Lets convert the coordinate value in human readable address.

CLGeocoder class provide service for convert coordinate to human readable address. By specify the latitude and longitude of a given location, you can use CLGeocoder to find a user-readable address.

Lets create a new method for getting human readable address of coordinate.

-(void) getReadableAddressFrom:(CLLocation *)location{
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        NSLog(@"Found placemarks: %@, error: %@", placemarks, error);
        if (error == nil && [placemarks count] > 0) {
            CLPlacemark *placemark = [placemarks lastObject];
            NSString *address = [NSString stringWithFormat:@"%@ %@\n%@ %@\n%@\n%@",placemark.subThoroughfare, placemark.thoroughfare,placemark.postalCode, placemark.locality,placemark.administrativeArea,placemark.country];
            NSLog(@"Address = %@", address);
        } else {
            NSLog(@"%@", error.debugDescription);
        }
    } ];
}


Inside 'didUpdateLocations' method add line of code to call above method.
[self getReadableAddressFrom:location];

Run the code and check the console, you can see address details.

Note :   For running the application on simulator set the default address of simulator.
In the menu bar, select “Debug” -> “Location” for setting the simulator location.


Thursday, 19 January 2017

Getting Current Location

The Core Location Framework provide the Objective-C interface for obtaining information about current location and heading(direction in which device is pointing) of user. By using this framework we can configure and schedule delivery of location and heading event and can define geographic regions.

Get current location:
CLLocationManager class have ability to deliver current location and heading event. We can use this class for start and stop delivery of  location and heading event. Its provide all event information through delegates methods(CLLocationManagerDelegate).

Here code snippet for getting current location

-(void) getCurrentLocation{
    //Create an instance of CLLocationManager
    CLLocationManager * locationManager = [[CLLocationManager alloc] init];

    // Set delegate
    locationManager.delegate = self;

   // set accuracy
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;

    //request for authorization
    if ([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        [locationManager requestWhenInUseAuthorization];
    }

    //start updating locations
    [locationManager startUpdatingLocation];
}


Now define the delegate method for getting location inforamation

-(void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    CLLocation *currentLocation = [locations lastObject];
    NSLog(@"Location latitude - %f",currentLocation.coordinate.latitude);
    NSLog(@"Location longitude - %f", currentLocation.coordinate.latitude);
}

// get error message to fetch location
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"didFailWithError: %@", error);
}

Its enough for getting current location of user.
Run the app.
First its prompt a message for getting accessibility to use current location(This message will appear  first time only). Click on allow button and  we can see location info in console area.

Note: For running the application on simulator, we need to do some extra setting, because by default simulator location is set to 'None' and this is the reason we are getting error message instead of current location information.
Now select 'Location' under Debug menu option of simulator, and choose 'custom location'. We can see some value for latitude and longitude, it is the position of Apple or Apple store,  we can change latitude and longitude value. Now click on 'Ok' and run the app again.
we can see  latitude and longitude value on console area.

Now we are getting current location of user in the form of latitude and longitude, but is it enough to find address/location by a user?  If i provide my latitude and longitude details to some one , is it possible to find my location for that?
We are getting current location information but its not understand for user. So we are going to convert location info in human readable format.

No need to worry about conversion because Core Location framework has ability to perform this task by CLGeocoder.
CLGeocoder:
The CLGeocoder class provides services for converting coordinate(latitude and longitude) to the user-friendly representation. A user-friendly representation of the coordinate typically consists of the street, city, state, and country information corresponding to the given location, but it may also contain a relevant point of interest, landmarks, or other identifying information. 

 Now back to code and update locationManager: didUpdateLocations: method with below code

 -(void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    //stop updating locations
    [manager stopUpdatingLocation];
    //get current location
    CLLocation *currentLocation = [locations lastObject];
    NSLog(@"Location latitude - %f",currentLocation.coordinate.latitude);
    NSLog(@"Location longitude - %f", currentLocation.coordinate.latitude);
 
    //convert coodinate to user-friendly representation
    CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
    [geoCoder reverseGeocodeLocation:locations.lastObject completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        CLPlacemark *placeMark = [placemarks lastObject];
        NSLog(@"name = %@", placeMark.name);
        NSLog(@"address dict = %@",placeMark.addressDictionary);
    }];
}


Run the application again.
Now we can see address details in console area.