How to find current location of user in mkmapview - ios

i want to find the current location of the user
below the code for finding coordinates from the well defined adress
hom can i find the current location of the user ..please help me
.h file
#import
#import
#interface ViewController : UIViewController<MKMapViewDelegate,CLLocationManagerDelegate>
#property(nonatomic,retain) MKMapView *myMapView;
#property (nonatomic, strong) CLGeocoder *myGeocoder;
#end
.m file
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
#interface ViewController ()
{
CLLocationManager *locationManager;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.myMapView.showsUserLocation=YES;
self.view.backgroundColor=[UIColor whiteColor];
self.myMapView=[[MKMapView alloc]initWithFrame:self.view.bounds];
self.myMapView.mapType=MKMapTypeHybrid;
self.myMapView.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
[self.view addSubview:self.myMapView];
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate=self;
locationManager.desiredAccuracy=kCLLocationAccuracyBest;
locationManager.distanceFilter=kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
NSString *oreillyAddress =#"india";
self.myGeocoder = [[CLGeocoder alloc] init];
[self.myGeocoder
geocodeAddressString:oreillyAddress completionHandler:^(NSArray *placemarks, NSError *error)
{
if ([placemarks count] > 0 && error == nil)
{
NSLog(#"Found %lu placemark(s).", (unsigned long)[placemarks count]);
CLPlacemark *firstPlacemark = [placemarks objectAtIndex:0]; NSLog(#"Longitude = %f", firstPlacemark.location.coordinate.longitude); NSLog(#"Latitude = %f", firstPlacemark.location.coordinate.latitude);
}
else if ([placemarks count] == 0 &&
error == nil){ NSLog(#"Found no placemarks.");
}
else if (error != nil){
NSLog(#"An error occurred = %#", error); }
}];
// Do any additional setup after loading the view, typically from a nib.
}
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
return YES;
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
float latitude=newLocation.coordinate.latitude;
float longitude=newLocation.coordinate.longitude;
NSLog(#"%f",latitude);
NSLog(#"%f",longitude);
[locationManager stopUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error
{
NSLog(#"error==>%#",error);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end

Define
CLLocationManager *lm;
CLLocation *location;
and then add the below mentioned code in your ViewDidLoad method
lm = [[CLLocationManager alloc] init];
lm.delegate = self;
lm.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
lm.distanceFilter = kCLDistanceFilterNone;
[lm startUpdatingLocation];
location = [lm location];
CLLocationCoordinate2D coordinate;
coordinate.longitude = location.coordinate.longitude;
coordinate.latitude = location.coordinate.latitude;
if((location.coordinate.longitude== 0.0 ) && (location.coordinate.latitude==0.0))
{
UIAlertView *alert2 = [[UIAlertView alloc ] initWithTitle:(#"Server Error:")message:(#"Internet Problem. Try Later !!!") delegate:nil cancelButtonTitle:nil otherButtonTitles:(#"OK"), nil];
[alert2 show];
}
else
{
coordinate = [location coordinate];
NSLog(#"Latitude of User is %f",coordinate.longitude);
NSLog(#"Longitude of User is %f",coordinate.latitude);
}

Use this
self.myMapView.showsUserLocation = YES;

If you are using the simulator, you would need to go to: Debug -> Location -> Customer. From there set your location to the desired test point.

To get user's current location in iOS 8
Add <CLLocationManagerDelegate> in .h file.
CLLocationManager *locationManager;
CLLocation *currentLocation;
locationManager = [CLLocationManager new];
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 && [CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedWhenInUse)
{
[locationManager requestAlwaysAuthorization];
}
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation *location = [locations lastObject];
NSLog(#"lat%f - lon%f", location.coordinate.latitude, location.coordinate.longitude);
NSString *currentLatitude = [NSString stringWithFormat:#"%f",location.coordinate.latitude];
NSString *currentLongitude = [NSString stringWithFormat:#"%f",location.coordinate.longitude];
[locationManager stopUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
switch (status)
{
case kCLAuthorizationStatusNotDetermined:
case kCLAuthorizationStatusRestricted:
case kCLAuthorizationStatusDenied:
{
[locationManager requestAlwaysAuthorization];
}
break;
default:
{
[locationManager startUpdatingLocation];
}
break;
}
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"Error while getting core location : %#",[error localizedFailureReason]);
if ([error code] == kCLErrorDenied)
{
//you had denied
}
[manager stopUpdatingLocation];
}
And In your plist file Dont forget to Enter a key
NSLocationAlwaysUsageDescription

Use this:
[self.mapview setShowsUserLocation:YES];

Related

How to use CoreLocation in iOS8/ios9?

I have programmed a project which use CoreLocation. In this project, I designed a button to get location. However it has no reaction when I click. Someone said it had changed in iOS 8. And I do what he said. But it did't work. Here is my git link: https://github.com/dwjdwj1216/MyLocations
Do like this in your CurrentLocationViewController, getLocation Method change like this:-
locationManager = [[CLLocationManager alloc] init];
[locationManager setDelegate:self];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBestForNavigation];
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
[locationManager requestAlwaysAuthorization];
}
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9) {
_locationManager.allowsBackgroundLocationUpdates = YES;
}
[locationManager setDistanceFilter:10.0f];
[locationManager startUpdatingLocation];
[locationManager startMonitoringSignificantLocationChanges];
To Get Current Location, Follow step..
First Set Two lines in .Plist File
NSLocationAlwaysUsageDescription : Allow location
NSLocationWhenInUseUsageDescription : Allow location
// AppDelegate.h
#import <CoreLocation/CoreLocation.h>
#property (nonatomic,retain) CLLocationManager *locationManager;
#import "AppDelegate.m"
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[self getCurrentLocation];
}
#pragma mark - CLLocatin delegate && Location Methdos
-(void)getCurrentLocation {
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
// To calculate loaction on 500 meters
/* CLLocationDistance kilometers = 0.5 1000.0; //user will be notified when distance is changed by 40km from current distance
locationManager.distanceFilter = kilometers; */
#ifdef __IPHONE_8_0
if (IS_OS_8_OR_LATER)
{
[locationManager requestAlwaysAuthorization];
}
#endif
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
//NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
[locationManager stopUpdatingLocation];
[self getCurrentCountry];
}
}
- (void)locationManager:(CLLocationManager*)aManager didFailWithError:(NSError *)anError {
switch([anError code])
{
case kCLErrorNetwork: // general, network-related error
{
}
break;
case kCLErrorDenied:{
}
break;
default:
{
}
break;
}
}
-(void)getCurrentCountry {
CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
[geoCoder reverseGeocodeLocation:locationManager.location
completionHandler:^(NSArray *placemarks, NSError *error) {
if (error == nil && [placemarks count] > 0)
{
NSLog(#"Current country: %#", [[placemarks objectAtIndex:0] country]);
NSLog(#"Current country code: %#", [[placemarks objectAtIndex:0] ISOcountryCode]);
NSLog(#"CountryCode=%#",GetContryCode);
SetContryCode
setBoolForCountryCode(YES);
NSLog(#"CountryCode=%#",GetContryCode);
}
}];
}

Core location not ask permission from the User and methods are not called

I'm trying to use core location in iOS 8 simulator, for that I added in my view an object of type 'MapKit View', In tab Atributtes inspector is checked the option show user location, In my project I'm using ARC, below is the structure of my code:
ViewController.h
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#interface MeuPrimeiroViewController : UIViewController <MKMapViewDelegate, CLLocationManagerDelegate>{
IBOutlet MKMapView *mapView;
}
#property (nonatomic, strong) CLLocationManager *locationManager;
#end
ViewController.m
#synthesize locationManager;
- (void)viewDidLoad {
[super viewDidLoad];
if ([CLLocationManager locationServicesEnabled]) {
NSLog(#"CLLocationManager locationServicesEnabled == ON");
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
// Check for iOS 8 Vs earlier version like iOS7.Otherwise code will
// crash on ios 7
if ([locationManager respondsToSelector:#selector
(requestWhenInUseAuthorization)]) {
[locationManager requestAlwaysAuthorization];
}
[locationManager startUpdatingLocation];
}else{
NSLog(#"CLLocationManager locationServicesEnabled == OFF");
}
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
NSLog(#"It works this method is called");
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
NSLog(#"Error: %#",[error description]);
}
In my info.plist file I add this key (NSLocationAlwaysUsageDescription) with this value (String).
If I go to attributes inspector and enable the checkbox (shows user location) I receive this error message, and core location methods are not called:
Trying to start MapKit location updates without prompting for location authorization. Must call -[CLLocationManager requestWhenInUseAuthorization] or -[CLLocationManager requestAlwaysAuthorization] first.
If I disable the checkbox, this message disappear, and core location methods not called again. I try to change the navigation to londom, try to change location to free run but nothing I tried worked, the methods do not continue to be called and never showed an empowering message to use core location. I believe I've already tried everything, anyone have any suggestions or a solution to this problem?
This is what i am doing for my app and working perfectly
- (void)startSignificantChangeUpdates {
if (nil == self.locationManager) {
self.locationManager = [[CLLocationManager alloc] init];
}
self.locationManager.delegate = self;
[self.locationManager startMonitoringSignificantLocationChanges];
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations {
CLLocation* location = [locations lastObject];
if (location) {
self.currentLocation = location;
NSString *latitude = [NSString stringWithFormat:#"%f", location.coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:#"%f", location.coordinate.longitude];
self.latLong = [NSString stringWithFormat:#"%#,%#",latitude, longitude];
}
if (!self.geocoder)
self.geocoder = [[CLGeocoder alloc] init];
[self.geocoder reverseGeocodeLocation:location completionHandler:
^(NSArray* placemarks, NSError* error){
if ([placemarks count] > 0) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
if (placemark.postalCode) {
self.currentZipCode = placemark.postalCode;
}
[[NSNotificationCenter defaultCenter] postNotificationName:#"zipCodeFoundNotification" object:self.currentZipCode userInfo:nil];
} else {
[[NSNotificationCenter defaultCenter] postNotificationName:#"zipCodeFoundNotification" object:nil userInfo:nil];
}
}];
}
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
if (status != kCLAuthorizationStatusAuthorized && status != kCLAuthorizationStatusNotDetermined) {
if (status == kCLAuthorizationStatusDenied){
self.currentZipCode = #"kCLAuthorizationStatusDenied";
} else if (status == kCLAuthorizationStatusRestricted) {
self.currentZipCode = #"kCLAuthorizationStatusRestricted";
}
}
}

How to get current location using CLLocationManager in iOS

I can already find the current location using latitude and longitude, but I would also like to be able to find the current location given a zip code.
Here is what I have so far:
.h
#import <MapKit/MapKit.h>
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#interface ViewController : UIViewController<CLLocationManagerDelegate>
{
CLLocationManager *locationManager;
CLLocation *currentLocation;
IBOutlet UILabel *label1;
IBOutlet UILabel *lable2;
}
#property (weak, nonatomic) IBOutlet MKMapView *myMapview;
#property (weak, nonatomic) IBOutlet UILabel *label2;
#property (weak, nonatomic) IBOutlet UILabel *lable1;
#end
.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
locationManager = [[CLLocationManager alloc]init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
_myMapview.showsUserLocation = YES;
[self->locationManager startUpdatingLocation];
CLLocation *location = [locationManager location];
CLLocationCoordinate2D coordinate = [location coordinate];
NSString *latitude = [NSString stringWithFormat:#"%f", coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:#"%f", coordinate.longitude];
//NSLog(#”dLatitude : %#”, latitude);
//NSLog(#”dLongitude : %#”,longitude);
NSLog(#"MY HOME :%#", latitude);
NSLog(#"MY HOME: %# ", longitude);
}
#pragma mark CLLocationManager Delegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
currentLocation = [locations objectAtIndex:0];
[locationManager stopUpdatingLocation];
[self->locationManager stopUpdatingLocation];
NSLog(#"my latitude :%f",currentLocation.coordinate.latitude);
NSLog(#"my longitude :%f",currentLocation.coordinate.longitude);
label1.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
lable2.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
NSLog(#"Detected Location : %f, %f", currentLocation.coordinate.latitude, currentLocation.coordinate.longitude);
CLGeocoder *geocoder = [[CLGeocoder alloc] init] ;
[geocoder reverseGeocodeLocation:currentLocation
completionHandler:^(NSArray *placemarks, NSError *error)
{
if (error)
{
NSLog(#"Geocode failed with error: %#", error);
return;
}
NSLog(#"Monday");
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(#"placemark.ISOcountryCode %#",placemark.ISOcountryCode);
}];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil)
{
label1.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
lable2.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Step 1: Import MobileCoreServices framework in .h File
#import <MobileCoreServices/MobileCoreServices.h>
Step 2: Add delegate CLLocationManagerDelegate
#interface yourViewController : UIViewController<CLLocationManagerDelegate>
{
CLLocationManager *locationManager;
CLLocation *currentLocation;
}
Step 3: Add this code in class file
- (void)viewDidLoad
{
[super viewDidLoad];
[self CurrentLocationIdentifier]; // call this method
}
Step 4: Method to get location
//------------ Current Location Address-----
-(void)CurrentLocationIdentifier
{
//---- For getting current gps location
locationManager = [CLLocationManager new];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
//------
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
currentLocation = [locations objectAtIndex:0];
[locationManager stopUpdatingLocation];
CLGeocoder *geocoder = [[CLGeocoder alloc] init] ;
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error)
{
if (!(error))
{
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(#"\nCurrent Location Detected\n");
NSLog(#"placemark %#",placemark);
NSString *locatedAt = [[placemark.addressDictionary valueForKey:#"FormattedAddressLines"] componentsJoinedByString:#", "];
NSString *Address = [[NSString alloc]initWithString:locatedAt];
NSString *Area = [[NSString alloc]initWithString:placemark.locality];
NSString *Country = [[NSString alloc]initWithString:placemark.country];
NSString *CountryArea = [NSString stringWithFormat:#"%#, %#", Area,Country];
NSLog(#"%#",CountryArea);
}
else
{
NSLog(#"Geocode failed with error %#", error);
NSLog(#"\nCurrent Location Not Detected\n");
//return;
CountryArea = NULL;
}
/*---- For more results
placemark.region);
placemark.country);
placemark.locality);
placemark.name);
placemark.ocean);
placemark.postalCode);
placemark.subLocality);
placemark.location);
------*/
}];
}
Here is a code to get user current location using block
1) #import <CoreLocation/CoreLocation.h>
2) <CLLocationManagerDelegate>
3) in .h file
//Location
typedef void(^locationBlock)();
//Location
-(void)GetCurrentLocation_WithBlock:(void(^)())block;
#property (nonatomic, strong) locationBlock _locationBlock;
#property (nonatomic,copy)CLLocationManager *locationManager;
#property (nonatomic)CLLocationCoordinate2D coordinate;
#property (nonatomic,strong) NSString *current_Lat;
#property (nonatomic,strong) NSString *current_Long;
4) in .m file
#pragma mark - CLLocationManager
-(void)GetCurrentLocation_WithBlock:(void(^)())block {
self._locationBlock = block;
_locationManager = [[CLLocationManager alloc] init];
[_locationManager setDelegate:self];
[_locationManager setDistanceFilter:kCLDistanceFilterNone];
[_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
if (IS_OS_8_OR_LATER) {
if ([_locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]) {
[_locationManager requestWhenInUseAuthorization];
[_locationManager requestAlwaysAuthorization];
}
}
[_locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation *currentLoc=[locations objectAtIndex:0];
_coordinate=currentLoc.coordinate;
_current_Lat = [NSString stringWithFormat:#"%f",currentLoc.coordinate.latitude];
_current_Long = [NSString stringWithFormat:#"%f",currentLoc.coordinate.longitude];
NSLog(#"here lat %# and here long %#",_current_Lat,_current_Long);
self._locationBlock();
[_locationManager stopUpdatingLocation];
_locationManager = nil;
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error {
}
5) Call function
- (void)viewDidLoad {
[super viewDidLoad];
[self GetCurrentLocation_WithBlock:^{
NSLog(#"Lat ::%f,Long ::%f",[self.current_Lat floatValue],[self.current_Long floatValue]);
}];
}
6) And add below line to .plist
Any one or both of below keys needs to be added in Info.plist file.
NSLocationWhenInUseUsageDescription
NSLocationAlwaysUsageDescription
if location permissions not asking when you first launch then you cant get your current location .
iOS8 has got us major API changes with the LocationsServices
Assuming [CLLocationManager locationServicesEnabled] return YES,
With the First Launch of the iOS App [both iOS7 and iOS8] - locationMangers(CLLocationManager)
You can call Google APIs Maps service to get the location using zipcode:
Just enter your zipcode in address={your zipcode}.

Cannot get latitude and longtidute with CoreLocation in Objective-C

I want to get the coordinates of the user, once user starts the app it should initialise GPS coordinates. I have followed this tutorial:
http://www.iosdevnotes.com/2011/10/ios-corelocation-tutorial/
I have created a class named CurrentLocationWithGPS
This is the header:
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
#interface CurrentLocationWithGPS : NSObject<CLLocationManagerDelegate>
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation;
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error;
- (void) getLocations;
- (Float32) latitude;
#property (strong, nonatomic) CLLocationManager *locationManager;
#property (strong, nonatomic) CLLocation *currentLocation;
#end
This is the implementation:
#import "CurrentLocationWithGPS.h"
#implementation CurrentLocationWithGPS
#synthesize locationManager, currentLocation;
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
self.currentLocation = newLocation;
if(newLocation.horizontalAccuracy <= 100.0f) { [locationManager stopUpdatingLocation]; }
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
if(error.code == kCLErrorDenied) {
[locationManager stopUpdatingLocation];
} else if(error.code == kCLErrorLocationUnknown) {
// retry
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error retrieving location"
message:[error description]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}
- (void) getLocations {
NSLog(#"GPS Location is initialising...");
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
[locationManager startUpdatingLocation];
NSLog(#"GPS Location is initialised...");
}
- (Float32) latitude {
return currentLocation.coordinate.latitude;
}
- (Float32) longitude {
return currentLocation.coordinate.longitude;
}
#end
I call the getLocations function in a separate thread so that it wouldn't block anything else. Here is how I call it from another class:
- (void)viewDidLoad
{
[super viewDidLoad];
NSThread *myThread =[[NSThread alloc]initWithTarget:self selector:#selector(locationSet) object:nil];
[myThread start];
}
- (void) locationSet {
CurrentLocationWithGPS *locationFind = [[CurrentLocationWithGPS alloc] init];
locationFind.getLocations;
NSLog(#"latitude is %f", locationFind.latitude);
}
Now the problem is both latitude and longitdute functions are returning 0.000, what am I missing here? I am developing for iOS6.1.
First conforms CLLocationManagerDelegate in .h file like this
#interface CurrentLocationWithGPS : NSObject<CLLocationManagerDelegate>
You need to set CLLocation's Delegate in this method.
- (void) getLocations
{
NSLog(#"GPS Location is initialising...");
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
NSLog(#"GPS Location is initialised...");
}
Do you getting the Current Location on the output . Or R you just trying to retrieve the Co-ordinates ?..
It's still confusing , anyhow
Put this part of code on Your getLocations method
I Hope that You are not at all checking with Location Services . You
Should enable the LocationServices for your app else You always get
null values Check with the Condition:
if ([CLLocationManager locationServicesEnabled])
{
}
For Example :
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
if ([CLLocationManager locationServicesEnabled])
{
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
}
location = [locationManager location];
CLLocationCoordinate2D coordinate = [location coordinate];;
NSString *str=[[NSString alloc] initWithFormat:#" latitude:%f longitude:%f",coordinate.latitude,coordinate.longitude];
And Let me know , .????

Update current location in all views from navbar locationButton

I have a custom navbar with a locateButton that is visible in every view
When a user taps the locateButton, I would like to update lat and long on every view. I've got it working in one view at a time, with the following code.
ViewController.m
- (UIBarButtonItem *)locateButton {
[locationButton addTarget:self action:#selector(locationPressed:) forControlEvents:UIControlEventTouchUpInside];
}
- (IBAction)locationPressed:(id)sender {
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:#"Error" message:#"Failed to Get Your Location" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
latLabel.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
longLabel.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
}
// Stop Location Manager
[locationManager stopUpdatingLocation];
// Reverse Geocoding
NSLog(#"Resolving the Address");
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
NSLog(#"Found placemarks: %#, error: %#", placemarks, error);
if (error == nil && [placemarks count] > 0) {
placemark = [placemarks lastObject];
addressLabel.text = [NSString stringWithFormat:#"%#, %#",
placemark.locality,
placemark.administrativeArea];
addressLabel.numberOfLines = 0;
} else {
NSLog(#"%#", error.debugDescription);
}
} ];
I'm trying to add a singleton to accomplish this.
In Location.h
// Location.h
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#interface Location : NSObject <CLLocationManagerDelegate>
#property (nonatomic, strong) CLLocationManager* locationManager;
+ (Location*)sharedSingleton;
#end
Then in Location.M
// Location.m
#import "Location.h"
#implementation Location
#synthesize locationManager;
- (id)init {
self = [super init];
if(self) {
self.locationManager = [CLLocationManager new];
[self.locationManager setDelegate:self];
[self.locationManager setDistanceFilter:kCLDistanceFilterNone];
[self.locationManager setHeadingFilter:kCLHeadingFilterNone];
[self.locationManager startUpdatingLocation];
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
//do any more customization to your location manager
}
return self;
}
+ (Location*)sharedSingleton {
static Location* sharedSingleton;
if(!sharedSingleton) {
#synchronized(sharedSingleton) {
sharedSingleton = [Location new];
}
}
return sharedSingleton;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"didUpdateToLocation: %#", newLocation);
[locationManager stopUpdatingLocation];
}
#end
How do I get my - (IBAction)locationPressed:(id)sender in another view let's say HomeViewController.m to call this locationManager method and also update the singleton value?
You might consider a singleton as your location manager and location manager delegate. There are a bunch of stackoverflow questions about creating singletons like this one: Singleton in iOS 5?.
Then when your user clicks that button, your singleton class will be called and updated and other views will look at that same singleton to get their location info.

Resources