Google Maps API: Getting coordinates of current location iOS

Alexyuiop picture Alexyuiop · Jun 12, 2013 · Viewed 35.3k times · Source

I am currently working with Google Maps API in my project. I am trying to set the default camera/zoom to the users location. I do this:

@implementation ViewController{

GMSMapView *mapView_;

}
@synthesize currentLatitude,currentLongitude;

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


}
- (void)loadView{

CLLocation *myLocation = mapView_.myLocation;

GMSMarker *marker = [[GMSMarker alloc] init];
marker.position = CLLocationCoordinate2DMake(myLocation.coordinate.latitude, myLocation.coordinate.longitude);
marker.title = @"Current Location";
marker.map = mapView_;
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:myLocation.coordinate.latitude
                                                        longitude:myLocation.coordinate.longitude
                                                             zoom:6];
mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];

self.view = mapView_;
   NSLog(@"%f, %f", myLocation.coordinate.latitude, myLocation.coordinate.longitude);

}

However, it does not work, since when I do

NSLog(@"%f, %f", myLocation.coordinate.latitude, myLocation.coordinate.longitude);

it returns 0, 0, and it does not give the current location coordinates. How can I properly get the user's coordinates?

Answer

DrDev picture DrDev · Jun 12, 2013

.h

#import <CoreLocation/CoreLocation.h>
@property(nonatomic,retain) CLLocationManager *locationManager;

.m

- (NSString *)deviceLocation 
{
NSString *theLocation = [NSString stringWithFormat:@"latitude: %f longitude: %f", locationManager.location.coordinate.latitude, locationManager.location.coordinate.longitude];
return theLocation;
}

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

answered here.