Search code examples
iosgoogle-mapsios7google-maps-sdk-ios

Unable to get current location coordinates using Google Maps API for iOS


I have tried the following code:

- (void)viewDidLoad
{
    [super viewDidLoad];
    mapView_.myLocationEnabled = YES;

    CLLocation *myLocation = mapView_.myLocation;
    NSLog(@"%f %f",myLocation.coordinate.latitude, myLocation.coordinate.longitude);
}

The output being logged is 0.000000 0.000000.

I have also checked in the settings that the location service is enabled and is also showing enabled for my app.

Please help me figure out where am I going wrong.


Solution

  • It is always show as 0, 0 in the viewDidLoad, you will have to use KVO to observe the coordinate. Try the following code:-

    -(void)viewWillAppear:(BOOL)animated{
        [super viewWillAppear:animated];
        [self.mapView addObserver:self forKeyPath:@"myLocation" options:NSKeyValueObservingOptionNew context: nil];
    }
    
    -(void)viewWillDisappear:(BOOL)animated{
        [super viewWillDisappear:animated];
        [self.mapView removeObserver:self forKeyPath:@"myLocation"];
    }
    
    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
    {
        if ([keyPath isEqualToString:@"myLocation"] && [object isKindOfClass:[GMSMapView class]])
        {
            NSLog(@"KVO triggered. Location Latitude: %f Longitude: %f",self.mapView.myLocation.coordinate.latitude,self.mapView.myLocation.coordinate.longitude);
        }
    }