mapview annotation not working in iphone 4s - ios

I don't know what's wrong with my code. This code work fine in iphone5 to higher version. In the first load of controller the map will show the country first then zoom in where the user point and the annotation show. Unfortunately, the iphone4s work different. It shows only the country then no more point or annotation show.
here is my code:
#import "ViewController.h"
#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
#interface ViewController ()
#property (weak, nonatomic) IBOutlet MKMapView *mapView;
#property (nonatomic,strong) CLLocationManager * locationManager;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.mapView.delegate = self;
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
#ifdef __IPHONE_8_0
if(IS_OS_8_OR_LATER) {
[self.locationManager requestWhenInUseAuthorization];
[self.locationManager requestAlwaysAuthorization];
}
#endif
[self.locationManager startUpdatingLocation];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
if (status == kCLAuthorizationStatusAuthorizedAlways || status == kCLAuthorizationStatusAuthorizedWhenInUse) {
self.mapView.showsUserLocation = YES;
}
}
#pragma mark Map View
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
static NSString *identifier = #"getLocation";
MKAnnotationView *annotationView = (MKPinAnnotationView *) [self.mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
if (annotationView == nil) {
annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier];
annotationView.enabled = YES;
annotationView.canShowCallout = YES;
} else {
annotationView.annotation = annotation;
}
return annotationView;
}
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
[self.mapView setShowsUserLocation:NO];
[self.mapView removeAnnotations:self.mapView.annotations];
CLLocation *currentLocation = [[CLLocation alloc] initWithLatitude:userLocation.coordinate.latitude longitude:userLocation.coordinate.longitude];
CLGeocoder * geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemark, NSError *error) {
NSString *annTitle = #"Address unknown";
if (placemark.count > 0)
{
CLPlacemark *topResult = [placemark objectAtIndex:0];
annTitle = [NSString stringWithFormat:#"%#", topResult.locality];
}
MKPointAnnotation *toAdd = [[MKPointAnnotation alloc]init];
toAdd.coordinate = userLocation.coordinate;
toAdd.title =annTitle;
[self.mapView addAnnotation:toAdd];
}];
}
-(void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views{
MKAnnotationView *annotationView = [views objectAtIndex:0];
id<MKAnnotation> mp = [annotationView annotation];
[UIView animateWithDuration:3.0 animations:^{
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance([mp coordinate] ,500,500);
[self.mapView setRegion:region animated:YES];
} completion:^(BOOL finished) {
[self.mapView selectAnnotation:mp animated:YES];
}];
}
and my viewcontroller.m
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#interface ViewController : UIViewController <MKMapViewDelegate, MKAnnotation,CLLocationManagerDelegate>
#property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
#end
but I get this error
Trying to start MapKit location updates without prompting for location authorization. Must call -[CLLocationManager requestWhenInUseAuthorization] or -[CLLocationManager requestAlwaysAuthorization] first.
The errors shows only for iphone4s. The version of my iphone4s is ios8.

This is happening because you have not made entry in plist as shown below.
If still not working, update code to below.
myMapView.delegate = self;
locationManager.delegate = self;
self.locationManager = [[CLLocationManager alloc] init];
#ifdef __IPHONE_8_0
if(IS_OS_8_OR_LATER) {
// Use one or the other, not both. Depending on what you put in info.plist
[self.locationManager requestWhenInUseAuthorization];
// [self.locationManager requestAlwaysAuthorization];
}
#endif
[self.locationManager startUpdatingLocation];
myMapView.showsUserLocation = YES;
[myMapView setMapType:MKMapTypeStandard];
[myMapView setZoomEnabled:YES];
[myMapView setScrollEnabled:YES];
Edit 1
As per your comment, you don't find info.plist.
You can find that in Supporting files.

Related

CLLocation Manager Delegates Not Called?

I have made one demo for getting Current Location.
I have used .GPX file for my current Location.
I have used Delegates method of CLLocation Method.
I have Also use Key "Privacy - Location When In Use Usage Description" in my plist file.
I know this question already asked so many time but could not able to get result.
code is
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#interface ViewController ()<CLLocationManagerDelegate,MKMapViewDelegate>
#property (nonatomic,assign)CLLocationCoordinate2D cordinateLocation;
#property (nonatomic,strong)MKPointAnnotation *point;
#property (nonatomic,weak)IBOutlet MKMapView *mapView;
#end
#implementation ViewController
CLLocationManager *locationManager;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
locationManager = [[CLLocationManager alloc]init];
locationManager.delegate = self;
self.mapView.delegate = self;
[self updateCurrentLocation];
}
- (void)updateCurrentLocation {
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
if ([locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]) {
[locationManager requestWhenInUseAuthorization];
}
[locationManager startUpdatingLocation];
}
//-(void)getCurrentLocation
//{
// [locationManager requestWhenInUseAuthorization];
// locationManager.desiredAccuracy = kCLLocationAccuracyBest;
// [locationManager startUpdatingHeading];
// [locationManager startUpdatingLocation];
//
//}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", error);
UIAlertController *errorAlert =[UIAlertController alertControllerWithTitle:#"Error" message:#"error reported" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *alertStyle = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:nil];
[errorAlert addAction:alertStyle];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
CLLocation *updatedLocation = [locations lastObject];
if(updatedLocation != nil)
{
self.cordinateLocation=CLLocationCoordinate2DMake(updatedLocation.coordinate.latitude, updatedLocation.coordinate.longitude);
[manager stopUpdatingLocation];
[self setCurrentLocationFocus];
}
else{
NSLog(#"Can't access desire location");
}
}
-(void)setCurrentLocationFocus{
MKCoordinateRegion region;
region.center = self.cordinateLocation;
//Adjust span as you like
MKCoordinateSpan span;
span.latitudeDelta = 1;
span.longitudeDelta = 1;
region.span = span;
[self.mapView setRegion:region animated:YES];
///Drop the pin on Current Locatio ////
self.point = [[MKPointAnnotation alloc] init];
self.point.coordinate = self.cordinateLocation;
self.point.title = #"FlockStation";
self.point.subtitle = #"It Department";
[self.mapView addAnnotation:self.point];
//set a new camera angle
MKMapCamera *newCamera=[[MKMapCamera alloc] init];
[newCamera setCenterCoordinate:self.cordinateLocation];
[newCamera setPitch:60.0]; ///For zooming purpose///
[newCamera setHeading:90]; ///For Compass Purpose ///
[newCamera setAltitude:100.0]; ///On which height you want to see your map ///
[self.mapView setCamera:newCamera animated:YES];
}
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
UIViewController *viewController = [mainStoryBoard instantiateViewControllerWithIdentifier:#"NewViewController"];
[self presentViewController:viewController animated:YES completion:nil];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
// self.updatedHeading.text = [NSString stringWithFormat:#"%f",newHeading.magneticHeading];
}
Help Me guys not able to get location.Because delegates method is not calling.
Every Time it called this method.
- (void)locationManager:(CLLocationManager *)manager didFailWithError:`(NSError *)error
You need to check permission of location. then after you can call the delegate methods.
- (void)viewDidLoad {
[super viewDidLoad];
locationManager=[[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
[locationManager requestWhenInUseAuthorization];
}
if ([CLLocationManager locationServicesEnabled]){
NSLog(#"Location Services Enabled");
if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusDenied){
alert = [[UIAlertView alloc] initWithTitle:#"Permission Denied"
message:#"To re-enable, please go to Settings and turn on Location Service for this app."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
CLLocation *currentLocation = newLocation;
txtlocations.text = [NSString stringWithFormat:#"%f & %f",currentLocation.coordinate.latitude, currentLocation.coordinate.longitude];
}
Tried with your code with little changes and its working fine.
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self updateCurrentLocation];
}
- (void)updateCurrentLocation {
if([CLLocationManager locationServicesEnabled] &&
[CLLocationManager authorizationStatus] != kCLAuthorizationStatusDenied) {
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate=self;
locationManager.desiredAccuracy=kCLLocationAccuracyBest;
locationManager.distanceFilter=kCLDistanceFilterNone;
[locationManager requestWhenInUseAuthorization];
[locationManager startMonitoringSignificantLocationChanges];
[locationManager startUpdatingLocation];
// show the map
} else {
// show error
}
}

Annotations on Map at lat/long (0,0) on device but located right in simulator

in my first iOS app I've got a map displaying annotations for several locations. It works perfectly in the simulator and looks like this:
But on all devices the annotations are not located right. They are all placed at latitude 0 and longitude 0.
Do you have any ideas?
Here is my Source Code:
MapViewController.m
//
// MapViewController.m
//
#import "MapViewController.h"
#import "AppDelegate.h"
#import "Location.h"
#import <MapKit/MapKit.h>
#import "Reachability.h"
#import "MyAnnotation.h"
#interface MapViewController ()
#end
#implementation MapViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.mapView.delegate = self;
//User location
self.locationManager = [[CLLocationManager alloc]init];
if ([self.locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]) {
[self.locationManager requestWhenInUseAuthorization];
}
[self.locationManager startUpdatingLocation];
[self loadOfflineMap];
[self addAnnotations:[(AppDelegate *)[[UIApplication sharedApplication] delegate] locations]];
//Set initial region
MKCoordinateRegion region = [self.mapView regionThatFits:MKCoordinateRegionMakeWithDistance(CLLocationCoordinate2DMake(53.868223, 10.689060), 3000, 3000)];
//Set initial locatoin if one is set
if(self.initialLocationName != nil){
for (id<MKAnnotation> annotation in [self.mapView annotations]) {
if([[annotation title] isEqualToString:self.initialLocationName]){
[self.mapView selectAnnotation:annotation animated:YES];
region = [self.mapView regionThatFits:MKCoordinateRegionMakeWithDistance([annotation coordinate], 500, 500)];
}
}
}
[self.mapView setRegion:region animated:YES];
//Layout stuff
self.locationName.font = [UIFont fontWithName:#"CenturyGothic" size:self.locationName.font.pointSize];
self.locationAddress.font = [UIFont fontWithName:#"CenturyGothic" size:self.locationAddress.font.pointSize];
}
-(void)addAnnotations:(NSMutableArray *)locations{
self.locationNameToAnnotation = [[NSMutableDictionary alloc] init];
for(Location *location in locations){
MyAnnotation *annotation = [[MyAnnotation alloc] initWithTitle:location.name AndCoordinate:CLLocationCoordinate2DMake([location.latitude doubleValue], [location.longitude doubleValue])];
[self.locationNameToAnnotation setObject:annotation forKey:location.name];
[self.mapView addAnnotation:annotation];
}
}
-(void)mapView:(MKMapView * )mapView didSelectAnnotationView:(MKAnnotationView * )view{
for(NSString *locationName in self.locationNameToAnnotation){
if([locationName isEqualToString:view.annotation.title]){
Location *location = [Location getLocationFromLocations:[(AppDelegate *)[[UIApplication sharedApplication] delegate] locations] byName:locationName];
self.locationName.text = location.name;
self.locationAddress.text = location.address;
}
}
self.locationInfoView.hidden = NO;
[self.mapView setCenterCoordinate:view.annotation.coordinate animated:YES];
}
-(void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view{
self.locationInfoView.hidden = YES;
}
-(void)loadOfflineMap{
self.mapView.delegate = self;
NSString *baseURL = [[[NSBundle mainBundle] bundleURL] absoluteString];
NSString *template = [baseURL stringByAppendingString:#"{x}-{y}.jpg"];
self.overlay = [[MKTileOverlay alloc] initWithURLTemplate:template];
self.overlay.canReplaceMapContent = YES;
self.overlay.minimumZ = 12;
self.overlay.maximumZ = 19;
[self.mapView addOverlay:self.overlay level:MKOverlayLevelAboveLabels];
}
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay {
return [[MKTileOverlayRenderer alloc] initWithTileOverlay:overlay];
}
- (IBAction)mapTypeChanged:(UISegmentedControl *)sender {
if(sender.selectedSegmentIndex == 1){
if([self checkIntetnetConnection] == YES){
[self.mapView removeOverlay:self.overlay];
}else{
sender.selectedSegmentIndex = 0;
}
}else if(sender.selectedSegmentIndex == 0){
[self.mapView addOverlay:self.overlay level:MKOverlayLevelAboveLabels];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(BOOL)checkIntetnetConnection{
Reachability *networkReachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [networkReachability currentReachabilityStatus];
if (networkStatus == NotReachable) {
//NSLog(#"There IS NO internet connection");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"No Internet" message:#"Sorry, please turn on your internet to access the online map" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
return NO;
} else {
//NSLog(#"There IS internet connection");
return YES;
}
}
#end
MyAnnotation.m
//
// MyAnnotation.m
//
#import "MyAnnotation.h"
#implementation MyAnnotation
#synthesize coordinate=_coordinate;
#synthesize title=_title;
-(id) initWithTitle:(NSString *) title AndCoordinate:(CLLocationCoordinate2D)coordinate
{
self = [super init];
_title = title;
_coordinate = coordinate;
return self;
}
#end
Edit 1
Locations Array Parsing from JSON, which works fine:
-(void)createLocations:(NSDictionary *)jsonLocations{
self.locations = [[NSMutableArray alloc] init];
for(NSDictionary *jsonLocation in jsonLocations){
Location *location = [[Location alloc] init];
[location setName:jsonLocation[#"name"]];
[location setId:jsonLocation[#"id"]];
[location setLatitude:[self getNumberFromString:jsonLocation[#"latitude"]]];
[location setLongitude:[self getNumberFromString:jsonLocation[#"longitude"]]];
[location setZoomlevel:jsonLocation[#"zoomlevel"]];
[location setAddress:jsonLocation[#"address"]];
[self.locations addObject:location];
}
}
I'd really appreciate all ideas. Probably it's an easy question but since I'm new to iOS Development I'm quite frustrated right now.
Cheers Thomas!

Default location in map-kit in ios

I am new to IOS i need to show default location with my latitude and longitude(12.940358, 80.208647).
with annotation pin.
.h file:
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#interface Map_view : UIViewController<MKMapViewDelegate,CLLocationManagerDelegate>{
CLLocationManager *locationmgr;
CLGeocoder *geocode;
CLPlacemark *placemark;
}
#property(nonatomic,retain)IBOutlet MKMapView *map11;
.m file:
#synthesize map11;
I don't no where to put my latitude and longitude and how to use please help me.
If you want to show your location with your lat & long with Annotation With Name.
Use this code.
- (void)viewDidLoad {
[super viewDidLoad];
mapVW.showsUserLocation = YES;
CLLocation *loc = [[CLLocation alloc]initWithLatitude:12.940358 longitude:80.208647];
[mapVW setCenterCoordinate:loc.coordinate animated:YES];
CLGeocoder *ceo = [[CLGeocoder alloc]init];
[ceo reverseGeocodeLocation:loc
completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
//String to hold address
NSString *locatedAt = [[placemark.addressDictionary valueForKey:#"FormattedAddressLines"] componentsJoinedByString:#", "];
NSString *cityName = placemark.locality;
MKPointAnnotation *annotationPoint = [[MKPointAnnotation alloc] init];
annotationPoint.coordinate = CLLocationCoordinate2DMake(12.940358, 80.208647);
annotationPoint.title = locatedAt;
MKCoordinateRegion region;
MKCoordinateSpan span1;
span1.latitudeDelta = 0.08;
span1.longitudeDelta = 0.08;
region.span = span1;
region.center = annotationPoint.coordinate;
[mapVW setRegion:region animated:TRUE];
[mapVW regionThatFits:region];
[mapVW addAnnotation:annotationPoint];
[mapVW selectAnnotation:annotationPoint animated:NO];
}
];
}
For centering on user location, you can use the following code:
[mapView setCenterCoordinate:mapView.userLocation.location.coordinate animated:YES];
For zooming on special locations, you should study how the regions (MKCoordinateRegion) are counted and work, count your latitude and longitude values for the region and display it using call:
[mapView setRegion:myRegion animated:YES];
Try the following code :
CLLocationCoordinate2D zoomLocation;
zoomLocation.latitude = 39.281516;
zoomLocation.longitude= -76.580806;
// 2
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, 0.5*METERS_PER_MILE, 0.5*METERS_PER_MILE);
// 3
[_mapView setRegion:viewRegion animated:YES];
This code will set your region in your map.. Then follow the steps to add annotation in your map..
// Add an annotation
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
point.coordinate = userLocation.coordinate; // Change coordinate as yours
point.title = #"Where am I?";
point.subtitle = #"I'm here!!!";
[self.mapView addAnnotation:point];
Hope it helps..
use this code it will help you:
- (void)location
{
_locationManger =[[CLLocationManager alloc]init];
_locationManger.distanceFilter=kCLDistanceFilterNone;
_locationManger.desiredAccuracy=kCLLocationAccuracyHundredMeters;
[_locationManger startUpdatingLocation];
[map11 setMapType:MKMapTypeStandard];
[map11 setZoomEnabled:YES];
[map11 setScrollEnabled:YES];
MKCoordinateRegion region={ {0.0,0.0 },{0.0,0.0}};
region.center.latitude = 12.940358 ;
region.center.longitude = 80.208647;
region.span.longitudeDelta = 20.20f;
region.span.latitudeDelta = 20.20f;
[map11 setRegion:region animated:YES];
[map11 setDelegate:sender];
}
It will show your desired location as
add this code in your viewdidload
//self.locationManager replace it with your locationmgr
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
#ifdef __IPHONE_8_0
if(IS_OS_8_OR_LATER) {
// Use one or the other, not both. Depending on what you put in info.plist
[self.locationManager requestWhenInUseAuthorization];
[self.locationManager requestAlwaysAuthorization];
}
#endif
[self.locationManager startUpdatingLocation];
mapView.showsUserLocation = YES;
[mapView setMapType:MKMapTypeStandard];
[mapView setZoomEnabled:YES];
[mapView setScrollEnabled:YES];
in viewdidappear add below code
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:YES];
self.locationManager.distanceFilter = kCLDistanceFilterNone;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[self.locationManager startUpdatingLocation];
NSLog(#"%#", [self deviceLocation]);
CLLocationCoordinate2D userLocation = CLLocationCoordinate2DMake( self.locationManager.location.coordinate.latitude, self.locationManager.location.coordinate.longitude);
MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
[annotation setCoordinate:userLocation];
[annotation setTitle:#"Your Location"];
[self.mapView addAnnotation:annotation];
//always show the name of annotation
[self.mapView selectAnnotation:annotation animated:YES];
//location 1
CLLocationCoordinate2D loc1Coord = CLLocationCoordinate2DMake(18.998250, 72.848734);//add your latitude and longitude here
MKPointAnnotation *annotation1 = [[MKPointAnnotation alloc] init];
[annotation1 setCoordinate:loc1Coord];
[annotation1 setTitle:#"title"];
[annotation1 setSubtitle:#"subtitle"];
[self.mapView addAnnotation:annotation1];
}
add this methods
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil;
MKAnnotationView *annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"loc"];
annotationView.canShowCallout = YES;
annotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
return annotationView;
}
Thats it, you can see your latitude and longitude in the map.Let me know if it is working or not?
first You have to set DELEGATE
and Import following in your .h file
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
after that make a property
#property(retain, nonatomic) CLLocationManager *locationManager;
and in ViewDidLoad
mapview.delegate = self;
and then You can do like belew
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 800, 800);
[self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];
// Add an annotation
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
point.coordinate = userLocation.coordinate;
point.title = #"Where am I?";
point.subtitle = #"I'm here!!!";
[self.mapView addAnnotation:point];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - to get User Current Location.
- (void)getUserLocation{
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
#ifdef __IPHONE_8_0
if([self getDeviceOSVersion].integerValue >= 8) {
// Use one or the other, not both. Depending on what you put in info.plist
[self.locationManager requestWhenInUseAuthorization];
[self.locationManager requestAlwaysAuthorization];
}
#endif
[self.locationManager startUpdatingLocation];
}
-(NSString *)getDeviceOSVersion{
return [NSString stringWithFormat:#"%#",[UIDevice currentDevice].systemVersion];
}
#pragma mark - CLLocationManagerDelegate
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
UIAlertController *errorAlert = [UIAlertController alertControllerWithTitle:#"ERROR" message:#"There was an error retrieving your location"preferredStyle:UIAlertControllerStyleAlert ];
UIAlertAction* ok = [UIAlertAction
actionWithTitle:#"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
[errorAlert dismissViewControllerAnimated:YES completion:nil];
}];
[errorAlert addAction:ok];
[self presentViewController:errorAlert animated:YES completion:nil];
NSLog(#"Error: %#",error.description);
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
CLLocation *currentLocation = [locations lastObject];
//currentLocation.coordinate.longitude = currentLocation.coordinate.longitude ;
// latitude = currentLocation.coordinate.latitude;
[self.locationManager stopUpdatingLocation];
}

IOS CLLocationManager is returning latitude: 0.000000 longitude: 0.000000

I have been trying to get the current location IOS8 and following thread Location Services not working in iOS 8 but getting the 00.00,00.00 instead current location. Any suggestion on where I am doing wrong.
ViewController.h
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
#interface ViewController : UIViewController <CLLocationManagerDelegate>
#property (strong, nonatomic) CLLocationManager *locationManager;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.distanceFilter = kCLDistanceFilterNone;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[self.locationManager startUpdatingLocation];
NSLog(#"%#", [self deviceLocation]);
CLLocation *location = [self.locationManager location];
// Configure the new event with information from the location
CLLocationCoordinate2D coordinate = [location coordinate];
NSString *latitude = [NSString stringWithFormat:#"%f", coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:#"%f", coordinate.longitude];
NSLog(#"%#",latitude);
NSLog(#"%#",longitude);
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)setUpMap
{
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
#ifdef __IPHONE_8_0
if(IS_OS_8_OR_LATER) {
// Use one or the other, not both. Depending on what you put in info.plist
[self.locationManager requestAlwaysAuthorization];
}
#endif
[self.locationManager startUpdatingLocation];
}
-(NSString *)deviceLocation
{
return [NSString stringWithFormat:#"latitude: %f longitude: %f", self.locationManager.location.coordinate.latitude, self.locationManager.location.coordinate.longitude];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
[manager stopUpdatingLocation];
CLLocationCoordinate2D coordinate_currentlocation = [newLocation coordinate];
float latitude_current = newLocation.coordinate.latitude;
float longitude_current = newLocation.coordinate.longitude;
NSLog(#"%f",latitude_current);
NSLog(#"%f",longitude_current);
NSLog(#"Current latitude :%f",coordinate_currentlocation.latitude);
NSLog(#"Current longitude :%f",coordinate_currentlocation.longitude);
}
#end
I have also added the following key in my info.plist
<key>NSLocationAlwaysUsageDescription</key>
<string>Your location is needed for this app.</string>
Add this string in InfoPlist.strings files
1) NSLocationWhenInUseUsageDescription
2) NSLocationAlwaysUsageDescription
Try this code
locationManagerApp=[[CLLocationManager alloc] init];
locationManagerApp.delegate = self;
locationManagerApp.distanceFilter = kCLDistanceFilterNone;
locationManagerApp.desiredAccuracy = kCLLocationAccuracyHundredMeters;
if([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
[locationManagerApp requestAlwaysAuthorization];
}
[locationManagerApp startUpdatingLocation];
CLLocation *location1 = [locationManagerApp location];
CLLocationCoordinate2D coordinate = [location1 coordinate];
self.latValue= [NSString stringWithFormat:#"%f", coordinate.latitude];
self.longValue = [NSString stringWithFormat:#"%f", coordinate.longitude];
NSLog(#"Latitude = %#", self.latValue);
NSLog(#"Longitude = %#", self.longValue);
And run your project in device. If you run project in simulator then not get lat/ long.
get the current location on simulator (select any one location).
There was a mistake in code, The function which actually checking the authorization never called. I moved my all the code to viewDidLoad as below and it worked. Thank you for looking into this.
- (void)viewDidLoad {
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
self.locationManager.distanceFilter = kCLDistanceFilterNone;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
#ifdef __IPHONE_8_0
if(IS_OS_8_OR_LATER)
{
[self.locationManager requestAlwaysAuthorization];
}
#endif
[self.locationManager startUpdatingLocation];
[self.locationManager startUpdatingLocation];
NSLog(#"%#", [self deviceLocation]);
[super viewDidLoad];
}

Core Location delegate methods not getting called in iOS 8.3 Xcode 6.3.1

I am trying to get the user's current location using the Core Location Framework in Xcode 6.3.1, I did following things:
Added Core Location Framework under Target-> General-> Linked Frameworks & Libraries
My ViewController.h file is as shown below,
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#interface ViewController : UIViewController<CLLocationManagerDelegate>
#property (weak, nonatomic) IBOutlet UILabel *lblLatitude;
#property (weak, nonatomic) IBOutlet UILabel *lblLongitude;
#property (weak, nonatomic) IBOutlet UILabel *lblAddress;
#property (strong, nonatomic) CLLocationManager *locationManager;
#end
My ViewController.m file is as shown below,
- (void)viewDidLoad
{
[super viewDidLoad];
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
if(IS_OS_8_OR_LATER){
NSUInteger code = [CLLocationManager authorizationStatus];
if (code == kCLAuthorizationStatusNotDetermined && ([self.locationManager respondsToSelector:#selector(requestAlwaysAuthorization)] || [self.locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)])) {
if([[NSBundle mainBundle] objectForInfoDictionaryKey:#"NSLocationAlwaysUsageDescription"]){
[self.locationManager requestAlwaysAuthorization];
} else if([[NSBundle mainBundle] objectForInfoDictionaryKey:#"NSLocationWhenInUseUsageDescription"]) {
[self.locationManager requestWhenInUseAuthorization];
} else {
NSLog(#"Info.plist does not contain NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription");
}
}
}
[self.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) {
lblLatitude.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
lblLongitude.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
}
}
#end
I had also added the following keys in my info.plist file
NSLocationWhenInUseUsageDescription
NSLocationAlwaysUsageDescription
Checked everything given here, here, here, here, and a lot more list
So, is anyone having a solution for this issue, kindly help. Have lost my mind searching for this for the whole day.
Yeah! Got the solution, Here is my whole code & things added to make it working. Special thanks to #MBarton for his great help. Also Thanks to # Vinh Nguyen for investing his precious time in solving my issue.
Added Core Location Framework under Target-> General-> Linked Frameworks & Libraries
Added in .plist file
NSLocationAlwaysUsageDescription
See Screenshot:
In my ViewController.h
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <MapKit/MKAnnotation.h>
// #define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
#interface ViewController : UIViewController <MKMapViewDelegate, CLLocationManagerDelegate>
{
__weak IBOutlet UINavigationItem *navigationItem;
}
#property (weak, nonatomic) IBOutlet MKMapView *mapView;
#property(nonatomic, retain) CLLocationManager *locationManager;
#end
Then in ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize mapView;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self setUpMap];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)setUpMap
{
mapView.delegate = self;
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
#ifdef __IPHONE_8_0
// if(IS_OS_8_OR_LATER) {
if ([self.locationManager respondsToSelector:#selector(requestAlwaysAuthorization)]) {
// Use one or the other, not both. Depending on what you put in info.plist
[self.locationManager requestAlwaysAuthorization];
}
#endif
[self.locationManager startUpdatingLocation];
mapView.showsUserLocation = YES;
[mapView setMapType:MKMapTypeStandard];
[mapView setZoomEnabled:YES];
[mapView setScrollEnabled:YES];
}
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:YES];
self.locationManager.distanceFilter = kCLDistanceFilterNone;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[self.locationManager startUpdatingLocation];
NSLog(#"%#", [self deviceLocation]);
//View Area
MKCoordinateRegion region = { { 0.0, 0.0 }, { 0.0, 0.0 } };
region.center.latitude = self.locationManager.location.coordinate.latitude;
region.center.longitude = self.locationManager.location.coordinate.longitude;
region.span.longitudeDelta = 0.005f;
region.span.longitudeDelta = 0.005f;
[mapView setRegion:region animated:YES];
}
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 800, 800);
[self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];
}
- (NSString *)deviceLocation {
return [NSString stringWithFormat:#"latitude: %f longitude: %f", self.locationManager.location.coordinate.latitude, self.locationManager.location.coordinate.longitude];
}
Ufff...! Got the solution after fighting with many codes since last 5 days...

Resources